blob: f2d666de126995be90578cb622bff9ddb6e94b52 [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,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000129/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000130/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000131/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000132/* 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 Stinner31be90b2010-04-22 19:38:16 +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 */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000172/* 0x000B, * LINE TABULATION */
173/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000174/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000175 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000176 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000177/* 0x001C, * FILE SEPARATOR */
178/* 0x001D, * GROUP SEPARATOR */
179/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000180 0, 0, 0, 0, 1, 1, 1, 0,
181 0, 0, 0, 0, 0, 0, 0, 0,
182 0, 0, 0, 0, 0, 0, 0, 0,
183 0, 0, 0, 0, 0, 0, 0, 0,
184 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000185
Benjamin Peterson14339b62009-01-31 16:36:08 +0000186 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,
192 0, 0, 0, 0, 0, 0, 0, 0,
193 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000194};
195
196
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000197Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000198PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000199{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000200#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000201 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000202#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 /* This is actually an illegal character, so it should
204 not be passed to unichr. */
205 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000206#endif
207}
208
Thomas Wouters477c8d52006-05-27 19:21:47 +0000209/* --- Bloom Filters ----------------------------------------------------- */
210
211/* stuff to implement simple "bloom filters" for Unicode characters.
212 to keep things simple, we use a single bitmask, using the least 5
213 bits from each unicode characters as the bit index. */
214
215/* the linebreak mask is set up by Unicode_Init below */
216
Antoine Pitrouf068f942010-01-13 14:19:12 +0000217#if LONG_BIT >= 128
218#define BLOOM_WIDTH 128
219#elif LONG_BIT >= 64
220#define BLOOM_WIDTH 64
221#elif LONG_BIT >= 32
222#define BLOOM_WIDTH 32
223#else
224#error "LONG_BIT is smaller than 32"
225#endif
226
Thomas Wouters477c8d52006-05-27 19:21:47 +0000227#define BLOOM_MASK unsigned long
228
229static BLOOM_MASK bloom_linebreak;
230
Antoine Pitrouf068f942010-01-13 14:19:12 +0000231#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
232#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000233
Benjamin Peterson29060642009-01-31 22:14:21 +0000234#define BLOOM_LINEBREAK(ch) \
235 ((ch) < 128U ? ascii_linebreak[(ch)] : \
236 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000237
238Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
239{
240 /* calculate simple bloom-style bitmask for a given unicode string */
241
Antoine Pitrouf068f942010-01-13 14:19:12 +0000242 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000243 Py_ssize_t i;
244
245 mask = 0;
246 for (i = 0; i < len; i++)
Antoine Pitrouf2c54842010-01-13 08:07:53 +0000247 BLOOM_ADD(mask, ptr[i]);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000248
249 return mask;
250}
251
252Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
253{
254 Py_ssize_t i;
255
256 for (i = 0; i < setlen; i++)
257 if (set[i] == chr)
258 return 1;
259
260 return 0;
261}
262
Benjamin Peterson29060642009-01-31 22:14:21 +0000263#define BLOOM_MEMBER(mask, chr, set, setlen) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000264 BLOOM(mask, chr) && unicode_member(chr, set, setlen)
265
Guido van Rossumd57fd912000-03-10 22:53:23 +0000266/* --- Unicode Object ----------------------------------------------------- */
267
268static
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000269int unicode_resize(register PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +0000270 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000271{
272 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000273
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000274 /* Shortcut if there's nothing much to do. */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000275 if (unicode->length == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000276 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000277
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000278 /* Resizing shared object (unicode_empty or single character
279 objects) in-place is not allowed. Use PyUnicode_Resize()
280 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000281
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 if (unicode == unicode_empty ||
Benjamin Peterson29060642009-01-31 22:14:21 +0000283 (unicode->length == 1 &&
284 unicode->str[0] < 256U &&
285 unicode_latin1[unicode->str[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000286 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000287 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000288 return -1;
289 }
290
Thomas Wouters477c8d52006-05-27 19:21:47 +0000291 /* We allocate one more byte to make sure the string is Ux0000 terminated.
292 The overallocation is also used by fastsearch, which assumes that it's
293 safe to look at str[length] (without making any assumptions about what
294 it contains). */
295
Guido van Rossumd57fd912000-03-10 22:53:23 +0000296 oldstr = unicode->str;
Christian Heimesb186d002008-03-18 15:15:01 +0000297 unicode->str = PyObject_REALLOC(unicode->str,
Benjamin Peterson29060642009-01-31 22:14:21 +0000298 sizeof(Py_UNICODE) * (length + 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000299 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000300 unicode->str = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000301 PyErr_NoMemory();
302 return -1;
303 }
304 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000305 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000306
Benjamin Peterson29060642009-01-31 22:14:21 +0000307 reset:
Guido van Rossumd57fd912000-03-10 22:53:23 +0000308 /* Reset the object caches */
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000309 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000310 Py_CLEAR(unicode->defenc);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000311 }
312 unicode->hash = -1;
Tim Petersced69f82003-09-16 20:30:58 +0000313
Guido van Rossumd57fd912000-03-10 22:53:23 +0000314 return 0;
315}
316
317/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000318 Ux0000 terminated; some code (e.g. new_identifier)
319 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000320
321 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000322 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000323
324*/
325
326static
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000328{
329 register PyUnicodeObject *unicode;
330
Thomas Wouters477c8d52006-05-27 19:21:47 +0000331 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000332 if (length == 0 && unicode_empty != NULL) {
333 Py_INCREF(unicode_empty);
334 return unicode_empty;
335 }
336
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000337 /* Ensure we won't overflow the size. */
338 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
339 return (PyUnicodeObject *)PyErr_NoMemory();
340 }
341
Guido van Rossumd57fd912000-03-10 22:53:23 +0000342 /* Unicode freelist & memory allocation */
Christian Heimes2202f872008-02-06 14:31:34 +0000343 if (free_list) {
344 unicode = free_list;
345 free_list = *(PyUnicodeObject **)unicode;
346 numfree--;
Benjamin Peterson29060642009-01-31 22:14:21 +0000347 if (unicode->str) {
348 /* Keep-Alive optimization: we only upsize the buffer,
349 never downsize it. */
350 if ((unicode->length < length) &&
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +0000351 unicode_resize(unicode, length) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000352 PyObject_DEL(unicode->str);
353 unicode->str = NULL;
354 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000355 }
Guido van Rossumad98db12001-06-14 17:52:02 +0000356 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000357 size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
358 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumad98db12001-06-14 17:52:02 +0000359 }
360 PyObject_INIT(unicode, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000361 }
362 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000363 size_t new_size;
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000364 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000365 if (unicode == NULL)
366 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +0000367 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
368 unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000369 }
370
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000371 if (!unicode->str) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000372 PyErr_NoMemory();
373 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000374 }
Jeremy Hyltond8082792003-09-16 19:41:39 +0000375 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000376 * the caller fails before initializing str -- unicode_resize()
377 * reads str[0], and the Keep-Alive optimization can keep memory
378 * allocated for str alive across a call to unicode_dealloc(unicode).
379 * We don't want unicode_resize to read uninitialized memory in
380 * that case.
381 */
Jeremy Hyltond8082792003-09-16 19:41:39 +0000382 unicode->str[0] = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000383 unicode->str[length] = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000384 unicode->length = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000385 unicode->hash = -1;
Walter Dörwald16807132007-05-25 13:52:07 +0000386 unicode->state = 0;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +0000387 unicode->defenc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000388 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000389
Benjamin Peterson29060642009-01-31 22:14:21 +0000390 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000391 /* XXX UNREF/NEWREF interface should be more symmetrical */
392 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000393 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000394 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000395 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000396}
397
398static
Guido van Rossum9475a232001-10-05 20:51:39 +0000399void unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000400{
Walter Dörwald16807132007-05-25 13:52:07 +0000401 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000402 case SSTATE_NOT_INTERNED:
403 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000404
Benjamin Peterson29060642009-01-31 22:14:21 +0000405 case SSTATE_INTERNED_MORTAL:
406 /* revive dead object temporarily for DelItem */
407 Py_REFCNT(unicode) = 3;
408 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
409 Py_FatalError(
410 "deletion of interned string failed");
411 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000412
Benjamin Peterson29060642009-01-31 22:14:21 +0000413 case SSTATE_INTERNED_IMMORTAL:
414 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000415
Benjamin Peterson29060642009-01-31 22:14:21 +0000416 default:
417 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000418 }
419
Guido van Rossum604ddf82001-12-06 20:03:56 +0000420 if (PyUnicode_CheckExact(unicode) &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000421 numfree < PyUnicode_MAXFREELIST) {
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000422 /* Keep-Alive optimization */
Benjamin Peterson29060642009-01-31 22:14:21 +0000423 if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
424 PyObject_DEL(unicode->str);
425 unicode->str = NULL;
426 unicode->length = 0;
427 }
428 if (unicode->defenc) {
Georg Brandl8ee604b2010-07-29 14:23:06 +0000429 Py_CLEAR(unicode->defenc);
Benjamin Peterson29060642009-01-31 22:14:21 +0000430 }
431 /* Add to free list */
Christian Heimes2202f872008-02-06 14:31:34 +0000432 *(PyUnicodeObject **)unicode = free_list;
433 free_list = unicode;
434 numfree++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000435 }
436 else {
Benjamin Peterson29060642009-01-31 22:14:21 +0000437 PyObject_DEL(unicode->str);
438 Py_XDECREF(unicode->defenc);
439 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000440 }
441}
442
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000443static
444int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000445{
446 register PyUnicodeObject *v;
447
448 /* Argument checks */
449 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000450 PyErr_BadInternalCall();
451 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000452 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000453 v = *unicode;
Christian Heimes90aa7642007-12-19 02:45:37 +0000454 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000455 PyErr_BadInternalCall();
456 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000457 }
458
459 /* Resizing unicode_empty and single character objects is not
460 possible since these are being shared. We simply return a fresh
461 copy with the same Unicode content. */
Tim Petersced69f82003-09-16 20:30:58 +0000462 if (v->length != length &&
Benjamin Peterson29060642009-01-31 22:14:21 +0000463 (v == unicode_empty || v->length == 1)) {
464 PyUnicodeObject *w = _PyUnicode_New(length);
465 if (w == NULL)
466 return -1;
467 Py_UNICODE_COPY(w->str, v->str,
468 length < v->length ? length : v->length);
469 Py_DECREF(*unicode);
470 *unicode = w;
471 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000472 }
473
474 /* Note that we don't have to modify *unicode for unshared Unicode
475 objects, since we can modify them in-place. */
476 return unicode_resize(v, length);
477}
478
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000479int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
480{
481 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
482}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000483
Guido van Rossumd57fd912000-03-10 22:53:23 +0000484PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
Benjamin Peterson29060642009-01-31 22:14:21 +0000485 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000486{
487 PyUnicodeObject *unicode;
488
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000489 /* If the Unicode data is known at construction time, we can apply
490 some optimizations which share commonly used objects. */
491 if (u != NULL) {
492
Benjamin Peterson29060642009-01-31 22:14:21 +0000493 /* Optimization for empty strings */
494 if (size == 0 && unicode_empty != NULL) {
495 Py_INCREF(unicode_empty);
496 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000497 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000498
499 /* Single character Unicode objects in the Latin-1 range are
500 shared when using this constructor */
501 if (size == 1 && *u < 256) {
502 unicode = unicode_latin1[*u];
503 if (!unicode) {
504 unicode = _PyUnicode_New(1);
505 if (!unicode)
506 return NULL;
507 unicode->str[0] = *u;
508 unicode_latin1[*u] = unicode;
509 }
510 Py_INCREF(unicode);
511 return (PyObject *)unicode;
512 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000513 }
Tim Petersced69f82003-09-16 20:30:58 +0000514
Guido van Rossumd57fd912000-03-10 22:53:23 +0000515 unicode = _PyUnicode_New(size);
516 if (!unicode)
517 return NULL;
518
519 /* Copy the Unicode data into the new object */
520 if (u != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +0000521 Py_UNICODE_COPY(unicode->str, u, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000522
523 return (PyObject *)unicode;
524}
525
Walter Dörwaldd2034312007-05-18 16:29:38 +0000526PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000527{
528 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +0000529
Benjamin Peterson14339b62009-01-31 16:36:08 +0000530 if (size < 0) {
531 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +0000532 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +0000533 return NULL;
534 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000535
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000536 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +0000537 some optimizations which share commonly used objects.
538 Also, this means the input must be UTF-8, so fall back to the
539 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000540 if (u != NULL) {
541
Benjamin Peterson29060642009-01-31 22:14:21 +0000542 /* Optimization for empty strings */
543 if (size == 0 && unicode_empty != NULL) {
544 Py_INCREF(unicode_empty);
545 return (PyObject *)unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000546 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000547
548 /* Single characters are shared when using this constructor.
549 Restrict to ASCII, since the input must be UTF-8. */
550 if (size == 1 && Py_CHARMASK(*u) < 128) {
551 unicode = unicode_latin1[Py_CHARMASK(*u)];
552 if (!unicode) {
553 unicode = _PyUnicode_New(1);
554 if (!unicode)
555 return NULL;
556 unicode->str[0] = Py_CHARMASK(*u);
557 unicode_latin1[Py_CHARMASK(*u)] = unicode;
558 }
559 Py_INCREF(unicode);
560 return (PyObject *)unicode;
561 }
Martin v. Löwis9c121062007-08-05 20:26:11 +0000562
563 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000564 }
565
Walter Dörwald55507312007-05-18 13:12:10 +0000566 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000567 if (!unicode)
568 return NULL;
569
Walter Dörwaldacaa5a12007-05-05 12:00:46 +0000570 return (PyObject *)unicode;
571}
572
Walter Dörwaldd2034312007-05-18 16:29:38 +0000573PyObject *PyUnicode_FromString(const char *u)
574{
575 size_t size = strlen(u);
576 if (size > PY_SSIZE_T_MAX) {
577 PyErr_SetString(PyExc_OverflowError, "input too long");
578 return NULL;
579 }
580
581 return PyUnicode_FromStringAndSize(u, size);
582}
583
Guido van Rossumd57fd912000-03-10 22:53:23 +0000584#ifdef HAVE_WCHAR_H
585
Mark Dickinson081dfee2009-03-18 14:47:41 +0000586#if (Py_UNICODE_SIZE == 2) && defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
587# define CONVERT_WCHAR_TO_SURROGATES
588#endif
589
590#ifdef CONVERT_WCHAR_TO_SURROGATES
591
592/* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
593 to convert from UTF32 to UTF16. */
594
595PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
596 Py_ssize_t size)
597{
598 PyUnicodeObject *unicode;
599 register Py_ssize_t i;
600 Py_ssize_t alloc;
601 const wchar_t *orig_w;
602
603 if (w == NULL) {
604 if (size == 0)
605 return PyUnicode_FromStringAndSize(NULL, 0);
606 PyErr_BadInternalCall();
607 return NULL;
608 }
609
610 if (size == -1) {
611 size = wcslen(w);
612 }
613
614 alloc = size;
615 orig_w = w;
616 for (i = size; i > 0; i--) {
617 if (*w > 0xFFFF)
618 alloc++;
619 w++;
620 }
621 w = orig_w;
622 unicode = _PyUnicode_New(alloc);
623 if (!unicode)
624 return NULL;
625
626 /* Copy the wchar_t data into the new object */
627 {
628 register Py_UNICODE *u;
629 u = PyUnicode_AS_UNICODE(unicode);
630 for (i = size; i > 0; i--) {
631 if (*w > 0xFFFF) {
632 wchar_t ordinal = *w++;
633 ordinal -= 0x10000;
634 *u++ = 0xD800 | (ordinal >> 10);
635 *u++ = 0xDC00 | (ordinal & 0x3FF);
636 }
637 else
638 *u++ = *w++;
639 }
640 }
641 return (PyObject *)unicode;
642}
643
644#else
645
Guido van Rossumd57fd912000-03-10 22:53:23 +0000646PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
Benjamin Peterson29060642009-01-31 22:14:21 +0000647 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000648{
649 PyUnicodeObject *unicode;
650
651 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +0000652 if (size == 0)
653 return PyUnicode_FromStringAndSize(NULL, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +0000654 PyErr_BadInternalCall();
655 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000656 }
657
Martin v. Löwis790465f2008-04-05 20:41:37 +0000658 if (size == -1) {
659 size = wcslen(w);
660 }
661
Guido van Rossumd57fd912000-03-10 22:53:23 +0000662 unicode = _PyUnicode_New(size);
663 if (!unicode)
664 return NULL;
665
666 /* Copy the wchar_t data into the new object */
667#ifdef HAVE_USABLE_WCHAR_T
668 memcpy(unicode->str, w, size * sizeof(wchar_t));
Tim Petersced69f82003-09-16 20:30:58 +0000669#else
Guido van Rossumd57fd912000-03-10 22:53:23 +0000670 {
Benjamin Peterson29060642009-01-31 22:14:21 +0000671 register Py_UNICODE *u;
672 register Py_ssize_t i;
673 u = PyUnicode_AS_UNICODE(unicode);
674 for (i = size; i > 0; i--)
675 *u++ = *w++;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000676 }
677#endif
678
679 return (PyObject *)unicode;
680}
681
Mark Dickinson081dfee2009-03-18 14:47:41 +0000682#endif /* CONVERT_WCHAR_TO_SURROGATES */
683
684#undef CONVERT_WCHAR_TO_SURROGATES
685
Walter Dörwald346737f2007-05-31 10:44:43 +0000686static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000687makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
688 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +0000689{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000690 *fmt++ = '%';
691 if (width) {
692 if (zeropad)
693 *fmt++ = '0';
694 fmt += sprintf(fmt, "%d", width);
695 }
696 if (precision)
697 fmt += sprintf(fmt, ".%d", precision);
698 if (longflag)
699 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000700 else if (longlongflag) {
701 /* longlongflag should only ever be nonzero on machines with
702 HAVE_LONG_LONG defined */
703#ifdef HAVE_LONG_LONG
704 char *f = PY_FORMAT_LONG_LONG;
705 while (*f)
706 *fmt++ = *f++;
707#else
708 /* we shouldn't ever get here */
709 assert(0);
710 *fmt++ = 'l';
711#endif
712 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000713 else if (size_tflag) {
714 char *f = PY_FORMAT_SIZE_T;
715 while (*f)
716 *fmt++ = *f++;
717 }
718 *fmt++ = c;
719 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +0000720}
721
Walter Dörwaldd2034312007-05-18 16:29:38 +0000722#define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
723
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000724/* size of fixed-size buffer for formatting single arguments */
725#define ITEM_BUFFER_LEN 21
726/* maximum number of characters required for output of %ld. 21 characters
727 allows for 64-bit integers (in decimal) and an optional sign. */
728#define MAX_LONG_CHARS 21
729/* maximum number of characters required for output of %lld.
730 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
731 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
732#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
733
Walter Dörwaldd2034312007-05-18 16:29:38 +0000734PyObject *
735PyUnicode_FromFormatV(const char *format, va_list vargs)
736{
Benjamin Peterson14339b62009-01-31 16:36:08 +0000737 va_list count;
738 Py_ssize_t callcount = 0;
739 PyObject **callresults = NULL;
740 PyObject **callresult = NULL;
741 Py_ssize_t n = 0;
742 int width = 0;
743 int precision = 0;
744 int zeropad;
745 const char* f;
746 Py_UNICODE *s;
747 PyObject *string;
748 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000749 char buffer[ITEM_BUFFER_LEN+1];
Benjamin Peterson14339b62009-01-31 16:36:08 +0000750 /* use abuffer instead of buffer, if we need more space
751 * (which can happen if there's a format specifier with width). */
752 char *abuffer = NULL;
753 char *realbuffer;
754 Py_ssize_t abuffersize = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000755 char fmt[61]; /* should be enough for %0width.precisionlld */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000756 const char *copy;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000757
758#ifdef VA_LIST_IS_ARRAY
Benjamin Peterson14339b62009-01-31 16:36:08 +0000759 Py_MEMCPY(count, vargs, sizeof(va_list));
Walter Dörwaldd2034312007-05-18 16:29:38 +0000760#else
761#ifdef __va_copy
Benjamin Peterson14339b62009-01-31 16:36:08 +0000762 __va_copy(count, vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +0000763#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000764 count = vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000765#endif
766#endif
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000767 /* step 1: count the number of %S/%R/%A/%s format specifications
768 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
769 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
770 * result in an array) */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000771 for (f = format; *f; f++) {
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000772 if (*f == '%') {
773 if (*(f+1)=='%')
774 continue;
775 if (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A')
776 ++callcount;
777 while (ISDIGIT((unsigned)*f))
778 width = (width*10) + *f++ - '0';
779 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
780 ;
781 if (*f == 's')
782 ++callcount;
783 }
Benjamin Peterson14339b62009-01-31 16:36:08 +0000784 }
785 /* step 2: allocate memory for the results of
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000786 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000787 if (callcount) {
788 callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
789 if (!callresults) {
790 PyErr_NoMemory();
791 return NULL;
792 }
793 callresult = callresults;
794 }
795 /* step 3: figure out how large a buffer we need */
796 for (f = format; *f; f++) {
797 if (*f == '%') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000798#ifdef HAVE_LONG_LONG
799 int longlongflag = 0;
800#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000801 const char* p = f;
802 width = 0;
803 while (ISDIGIT((unsigned)*f))
804 width = (width*10) + *f++ - '0';
805 while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
806 ;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000807
Benjamin Peterson14339b62009-01-31 16:36:08 +0000808 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
809 * they don't affect the amount of space we reserve.
810 */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000811 if (*f == 'l') {
812 if (f[1] == 'd' || f[1] == 'u') {
813 ++f;
814 }
815#ifdef HAVE_LONG_LONG
816 else if (f[1] == 'l' &&
817 (f[2] == 'd' || f[2] == 'u')) {
818 longlongflag = 1;
819 f += 2;
820 }
821#endif
822 }
823 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000824 ++f;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000825 }
Walter Dörwaldd2034312007-05-18 16:29:38 +0000826
Benjamin Peterson14339b62009-01-31 16:36:08 +0000827 switch (*f) {
828 case 'c':
829 (void)va_arg(count, int);
830 /* fall through... */
831 case '%':
832 n++;
833 break;
834 case 'd': case 'u': case 'i': case 'x':
835 (void) va_arg(count, int);
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000836#ifdef HAVE_LONG_LONG
837 if (longlongflag) {
838 if (width < MAX_LONG_LONG_CHARS)
839 width = MAX_LONG_LONG_CHARS;
840 }
841 else
842#endif
843 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
844 including sign. Decimal takes the most space. This
845 isn't enough for octal. If a width is specified we
846 need more (which we allocate later). */
847 if (width < MAX_LONG_CHARS)
848 width = MAX_LONG_CHARS;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000849 n += width;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000850 /* XXX should allow for large precision here too. */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000851 if (abuffersize < width)
852 abuffersize = width;
853 break;
854 case 's':
855 {
856 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +0000857 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +0000858 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
859 if (!str)
860 goto fail;
861 n += PyUnicode_GET_SIZE(str);
862 /* Remember the str and switch to the next slot */
863 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000864 break;
865 }
866 case 'U':
867 {
868 PyObject *obj = va_arg(count, PyObject *);
869 assert(obj && PyUnicode_Check(obj));
870 n += PyUnicode_GET_SIZE(obj);
871 break;
872 }
873 case 'V':
874 {
875 PyObject *obj = va_arg(count, PyObject *);
876 const char *str = va_arg(count, const char *);
877 assert(obj || str);
878 assert(!obj || PyUnicode_Check(obj));
879 if (obj)
880 n += PyUnicode_GET_SIZE(obj);
881 else
882 n += strlen(str);
883 break;
884 }
885 case 'S':
886 {
887 PyObject *obj = va_arg(count, PyObject *);
888 PyObject *str;
889 assert(obj);
890 str = PyObject_Str(obj);
891 if (!str)
892 goto fail;
893 n += PyUnicode_GET_SIZE(str);
894 /* Remember the str and switch to the next slot */
895 *callresult++ = str;
896 break;
897 }
898 case 'R':
899 {
900 PyObject *obj = va_arg(count, PyObject *);
901 PyObject *repr;
902 assert(obj);
903 repr = PyObject_Repr(obj);
904 if (!repr)
905 goto fail;
906 n += PyUnicode_GET_SIZE(repr);
907 /* Remember the repr and switch to the next slot */
908 *callresult++ = repr;
909 break;
910 }
911 case 'A':
912 {
913 PyObject *obj = va_arg(count, PyObject *);
914 PyObject *ascii;
915 assert(obj);
916 ascii = PyObject_ASCII(obj);
917 if (!ascii)
918 goto fail;
919 n += PyUnicode_GET_SIZE(ascii);
920 /* Remember the repr and switch to the next slot */
921 *callresult++ = ascii;
922 break;
923 }
924 case 'p':
925 (void) va_arg(count, int);
926 /* maximum 64-bit pointer representation:
927 * 0xffffffffffffffff
928 * so 19 characters is enough.
929 * XXX I count 18 -- what's the extra for?
930 */
931 n += 19;
932 break;
933 default:
934 /* if we stumble upon an unknown
935 formatting code, copy the rest of
936 the format string to the output
937 string. (we cannot just skip the
938 code, since there's no way to know
939 what's in the argument list) */
940 n += strlen(p);
941 goto expand;
942 }
943 } else
944 n++;
945 }
Benjamin Peterson29060642009-01-31 22:14:21 +0000946 expand:
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000947 if (abuffersize > ITEM_BUFFER_LEN) {
948 /* add 1 for sprintf's trailing null byte */
949 abuffer = PyObject_Malloc(abuffersize + 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +0000950 if (!abuffer) {
951 PyErr_NoMemory();
952 goto fail;
953 }
954 realbuffer = abuffer;
955 }
956 else
957 realbuffer = buffer;
958 /* step 4: fill the buffer */
959 /* Since we've analyzed how much space we need for the worst case,
960 we don't have to resize the string.
961 There can be no errors beyond this point. */
962 string = PyUnicode_FromUnicode(NULL, n);
963 if (!string)
964 goto fail;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000965
Benjamin Peterson14339b62009-01-31 16:36:08 +0000966 s = PyUnicode_AS_UNICODE(string);
967 callresult = callresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +0000968
Benjamin Peterson14339b62009-01-31 16:36:08 +0000969 for (f = format; *f; f++) {
970 if (*f == '%') {
971 const char* p = f++;
972 int longflag = 0;
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000973 int longlongflag = 0;
Benjamin Peterson14339b62009-01-31 16:36:08 +0000974 int size_tflag = 0;
975 zeropad = (*f == '0');
976 /* parse the width.precision part */
977 width = 0;
978 while (ISDIGIT((unsigned)*f))
979 width = (width*10) + *f++ - '0';
980 precision = 0;
981 if (*f == '.') {
982 f++;
983 while (ISDIGIT((unsigned)*f))
984 precision = (precision*10) + *f++ - '0';
985 }
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000986 /* Handle %ld, %lu, %lld and %llu. */
987 if (*f == 'l') {
988 if (f[1] == 'd' || f[1] == 'u') {
989 longflag = 1;
990 ++f;
991 }
992#ifdef HAVE_LONG_LONG
993 else if (f[1] == 'l' &&
994 (f[2] == 'd' || f[2] == 'u')) {
995 longlongflag = 1;
996 f += 2;
997 }
998#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +0000999 }
1000 /* handle the size_t flag. */
1001 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
1002 size_tflag = 1;
1003 ++f;
1004 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001005
Benjamin Peterson14339b62009-01-31 16:36:08 +00001006 switch (*f) {
1007 case 'c':
1008 *s++ = va_arg(vargs, int);
1009 break;
1010 case 'd':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001011 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1012 width, precision, 'd');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001013 if (longflag)
1014 sprintf(realbuffer, fmt, va_arg(vargs, long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001015#ifdef HAVE_LONG_LONG
1016 else if (longlongflag)
1017 sprintf(realbuffer, fmt, va_arg(vargs, PY_LONG_LONG));
1018#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001019 else if (size_tflag)
1020 sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
1021 else
1022 sprintf(realbuffer, fmt, va_arg(vargs, int));
1023 appendstring(realbuffer);
1024 break;
1025 case 'u':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001026 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1027 width, precision, 'u');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001028 if (longflag)
1029 sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001030#ifdef HAVE_LONG_LONG
1031 else if (longlongflag)
1032 sprintf(realbuffer, fmt, va_arg(vargs,
1033 unsigned PY_LONG_LONG));
1034#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001035 else if (size_tflag)
1036 sprintf(realbuffer, fmt, va_arg(vargs, size_t));
1037 else
1038 sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
1039 appendstring(realbuffer);
1040 break;
1041 case 'i':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001042 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'i');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001043 sprintf(realbuffer, fmt, va_arg(vargs, int));
1044 appendstring(realbuffer);
1045 break;
1046 case 'x':
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001047 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001048 sprintf(realbuffer, fmt, va_arg(vargs, int));
1049 appendstring(realbuffer);
1050 break;
1051 case 's':
1052 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001053 /* unused, since we already have the result */
1054 (void) va_arg(vargs, char *);
1055 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(*callresult),
1056 PyUnicode_GET_SIZE(*callresult));
1057 s += PyUnicode_GET_SIZE(*callresult);
1058 /* We're done with the unicode()/repr() => forget it */
1059 Py_DECREF(*callresult);
1060 /* switch to next unicode()/repr() result */
1061 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001062 break;
1063 }
1064 case 'U':
1065 {
1066 PyObject *obj = va_arg(vargs, PyObject *);
1067 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1068 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1069 s += size;
1070 break;
1071 }
1072 case 'V':
1073 {
1074 PyObject *obj = va_arg(vargs, PyObject *);
1075 const char *str = va_arg(vargs, const char *);
1076 if (obj) {
1077 Py_ssize_t size = PyUnicode_GET_SIZE(obj);
1078 Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
1079 s += size;
1080 } else {
1081 appendstring(str);
1082 }
1083 break;
1084 }
1085 case 'S':
1086 case 'R':
1087 {
1088 Py_UNICODE *ucopy;
1089 Py_ssize_t usize;
1090 Py_ssize_t upos;
1091 /* unused, since we already have the result */
1092 (void) va_arg(vargs, PyObject *);
1093 ucopy = PyUnicode_AS_UNICODE(*callresult);
1094 usize = PyUnicode_GET_SIZE(*callresult);
1095 for (upos = 0; upos<usize;)
1096 *s++ = ucopy[upos++];
1097 /* We're done with the unicode()/repr() => forget it */
1098 Py_DECREF(*callresult);
1099 /* switch to next unicode()/repr() result */
1100 ++callresult;
1101 break;
1102 }
1103 case 'p':
1104 sprintf(buffer, "%p", va_arg(vargs, void*));
1105 /* %p is ill-defined: ensure leading 0x. */
1106 if (buffer[1] == 'X')
1107 buffer[1] = 'x';
1108 else if (buffer[1] != 'x') {
1109 memmove(buffer+2, buffer, strlen(buffer)+1);
1110 buffer[0] = '0';
1111 buffer[1] = 'x';
1112 }
1113 appendstring(buffer);
1114 break;
1115 case '%':
1116 *s++ = '%';
1117 break;
1118 default:
1119 appendstring(p);
1120 goto end;
1121 }
1122 } else
1123 *s++ = *f;
1124 }
Walter Dörwaldd2034312007-05-18 16:29:38 +00001125
Benjamin Peterson29060642009-01-31 22:14:21 +00001126 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001127 if (callresults)
1128 PyObject_Free(callresults);
1129 if (abuffer)
1130 PyObject_Free(abuffer);
1131 PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
1132 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001133 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001134 if (callresults) {
1135 PyObject **callresult2 = callresults;
1136 while (callresult2 < callresult) {
1137 Py_DECREF(*callresult2);
1138 ++callresult2;
1139 }
1140 PyObject_Free(callresults);
1141 }
1142 if (abuffer)
1143 PyObject_Free(abuffer);
1144 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001145}
1146
1147#undef appendstring
1148
1149PyObject *
1150PyUnicode_FromFormat(const char *format, ...)
1151{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001152 PyObject* ret;
1153 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001154
1155#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001156 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001157#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001158 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001159#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001160 ret = PyUnicode_FromFormatV(format, vargs);
1161 va_end(vargs);
1162 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001163}
1164
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001166 wchar_t *w,
1167 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001168{
1169 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001170 PyErr_BadInternalCall();
1171 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001172 }
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001173
1174 /* If possible, try to copy the 0-termination as well */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001175 if (size > PyUnicode_GET_SIZE(unicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00001176 size = PyUnicode_GET_SIZE(unicode) + 1;
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001177
Guido van Rossumd57fd912000-03-10 22:53:23 +00001178#ifdef HAVE_USABLE_WCHAR_T
1179 memcpy(w, unicode->str, size * sizeof(wchar_t));
1180#else
1181 {
Benjamin Peterson29060642009-01-31 22:14:21 +00001182 register Py_UNICODE *u;
1183 register Py_ssize_t i;
1184 u = PyUnicode_AS_UNICODE(unicode);
1185 for (i = size; i > 0; i--)
1186 *w++ = *u++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001187 }
1188#endif
1189
Marc-André Lemburga9cadcd2004-11-22 13:02:31 +00001190 if (size > PyUnicode_GET_SIZE(unicode))
1191 return PyUnicode_GET_SIZE(unicode);
1192 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001193 return size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001194}
1195
1196#endif
1197
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001198PyObject *PyUnicode_FromOrdinal(int ordinal)
1199{
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001200 Py_UNICODE s[2];
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001201
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001202 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001203 PyErr_SetString(PyExc_ValueError,
1204 "chr() arg not in range(0x110000)");
1205 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001206 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00001207
1208#ifndef Py_UNICODE_WIDE
1209 if (ordinal > 0xffff) {
1210 ordinal -= 0x10000;
1211 s[0] = 0xD800 | (ordinal >> 10);
1212 s[1] = 0xDC00 | (ordinal & 0x3FF);
1213 return PyUnicode_FromUnicode(s, 2);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001214 }
1215#endif
1216
Hye-Shik Chang40574832004-04-06 07:24:51 +00001217 s[0] = (Py_UNICODE)ordinal;
1218 return PyUnicode_FromUnicode(s, 1);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00001219}
1220
Guido van Rossumd57fd912000-03-10 22:53:23 +00001221PyObject *PyUnicode_FromObject(register PyObject *obj)
1222{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001223 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00001224 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001225 if (PyUnicode_CheckExact(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001226 Py_INCREF(obj);
1227 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001228 }
1229 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001230 /* For a Unicode subtype that's not a Unicode object,
1231 return a true Unicode object with the same data. */
1232 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
1233 PyUnicode_GET_SIZE(obj));
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001234 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001235 PyErr_Format(PyExc_TypeError,
1236 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00001237 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001238 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001239}
1240
1241PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00001242 const char *encoding,
1243 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001244{
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001245 const char *s = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001246 Py_ssize_t len;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001247 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00001248
Guido van Rossumd57fd912000-03-10 22:53:23 +00001249 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001250 PyErr_BadInternalCall();
1251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001252 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001253
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001254 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001255 PyErr_SetString(PyExc_TypeError,
1256 "decoding str is not supported");
1257 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001258 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001259
1260 /* Coerce object */
Christian Heimes72b710a2008-05-26 13:28:38 +00001261 if (PyBytes_Check(obj)) {
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001262 s = PyBytes_AS_STRING(obj);
1263 len = PyBytes_GET_SIZE(obj);
1264 }
1265 else if (PyByteArray_Check(obj)) {
1266 s = PyByteArray_AS_STRING(obj);
1267 len = PyByteArray_GET_SIZE(obj);
1268 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00001269 else if (PyObject_AsCharBuffer(obj, &s, &len)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001270 /* Overwrite the error message with something more useful in
1271 case of a TypeError. */
1272 if (PyErr_ExceptionMatches(PyExc_TypeError))
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001273 PyErr_Format(PyExc_TypeError,
Georg Brandl952867a2010-06-27 10:17:12 +00001274 "coercing to str: need bytes, bytearray or char buffer, "
Benjamin Peterson29060642009-01-31 22:14:21 +00001275 "%.80s found",
1276 Py_TYPE(obj)->tp_name);
1277 goto onError;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00001278 }
Tim Petersced69f82003-09-16 20:30:58 +00001279
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001280 /* Convert to Unicode */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001281 if (len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001282 Py_INCREF(unicode_empty);
1283 v = (PyObject *)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001284 }
Tim Petersced69f82003-09-16 20:30:58 +00001285 else
Benjamin Peterson29060642009-01-31 22:14:21 +00001286 v = PyUnicode_Decode(s, len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001287
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001288 return v;
1289
Benjamin Peterson29060642009-01-31 22:14:21 +00001290 onError:
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00001291 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001292}
1293
Victor Stinner600d3be2010-06-10 12:00:55 +00001294/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00001295 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
1296 1 on success. */
1297static int
1298normalize_encoding(const char *encoding,
1299 char *lower,
1300 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001301{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001302 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00001303 char *l;
1304 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001305
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001306 e = encoding;
1307 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00001308 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00001309 while (*e) {
1310 if (l == l_end)
1311 return 0;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001312 if (ISUPPER(*e)) {
1313 *l++ = TOLOWER(*e++);
1314 }
1315 else if (*e == '_') {
1316 *l++ = '-';
1317 e++;
1318 }
1319 else {
1320 *l++ = *e++;
1321 }
1322 }
1323 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00001324 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00001325}
1326
1327PyObject *PyUnicode_Decode(const char *s,
1328 Py_ssize_t size,
1329 const char *encoding,
1330 const char *errors)
1331{
1332 PyObject *buffer = NULL, *unicode;
1333 Py_buffer info;
1334 char lower[11]; /* Enough for any encoding shortcut */
1335
1336 if (encoding == NULL)
1337 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001338
1339 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001340 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1341 if (strcmp(lower, "utf-8") == 0)
1342 return PyUnicode_DecodeUTF8(s, size, errors);
1343 else if ((strcmp(lower, "latin-1") == 0) ||
1344 (strcmp(lower, "iso-8859-1") == 0))
1345 return PyUnicode_DecodeLatin1(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001346#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001347 else if (strcmp(lower, "mbcs") == 0)
1348 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001349#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001350 else if (strcmp(lower, "ascii") == 0)
1351 return PyUnicode_DecodeASCII(s, size, errors);
1352 else if (strcmp(lower, "utf-16") == 0)
1353 return PyUnicode_DecodeUTF16(s, size, errors, 0);
1354 else if (strcmp(lower, "utf-32") == 0)
1355 return PyUnicode_DecodeUTF32(s, size, errors, 0);
1356 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001357
1358 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001359 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00001360 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00001361 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00001362 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001363 if (buffer == NULL)
1364 goto onError;
1365 unicode = PyCodec_Decode(buffer, encoding, errors);
1366 if (unicode == NULL)
1367 goto onError;
1368 if (!PyUnicode_Check(unicode)) {
1369 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001370 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00001371 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001372 Py_DECREF(unicode);
1373 goto onError;
1374 }
1375 Py_DECREF(buffer);
1376 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001377
Benjamin Peterson29060642009-01-31 22:14:21 +00001378 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001379 Py_XDECREF(buffer);
1380 return NULL;
1381}
1382
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001383PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
1384 const char *encoding,
1385 const char *errors)
1386{
1387 PyObject *v;
1388
1389 if (!PyUnicode_Check(unicode)) {
1390 PyErr_BadArgument();
1391 goto onError;
1392 }
1393
1394 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001395 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001396
1397 /* Decode via the codec registry */
1398 v = PyCodec_Decode(unicode, encoding, errors);
1399 if (v == NULL)
1400 goto onError;
1401 return v;
1402
Benjamin Peterson29060642009-01-31 22:14:21 +00001403 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001404 return NULL;
1405}
1406
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001407PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
1408 const char *encoding,
1409 const char *errors)
1410{
1411 PyObject *v;
1412
1413 if (!PyUnicode_Check(unicode)) {
1414 PyErr_BadArgument();
1415 goto onError;
1416 }
1417
1418 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001419 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001420
1421 /* Decode via the codec registry */
1422 v = PyCodec_Decode(unicode, encoding, errors);
1423 if (v == NULL)
1424 goto onError;
1425 if (!PyUnicode_Check(v)) {
1426 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001427 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001428 Py_TYPE(v)->tp_name);
1429 Py_DECREF(v);
1430 goto onError;
1431 }
1432 return v;
1433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001435 return NULL;
1436}
1437
Guido van Rossumd57fd912000-03-10 22:53:23 +00001438PyObject *PyUnicode_Encode(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001439 Py_ssize_t size,
1440 const char *encoding,
1441 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001442{
1443 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00001444
Guido van Rossumd57fd912000-03-10 22:53:23 +00001445 unicode = PyUnicode_FromUnicode(s, size);
1446 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001447 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001448 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
1449 Py_DECREF(unicode);
1450 return v;
1451}
1452
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001453PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
1454 const char *encoding,
1455 const char *errors)
1456{
1457 PyObject *v;
1458
1459 if (!PyUnicode_Check(unicode)) {
1460 PyErr_BadArgument();
1461 goto onError;
1462 }
1463
1464 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001465 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001466
1467 /* Encode via the codec registry */
1468 v = PyCodec_Encode(unicode, encoding, errors);
1469 if (v == NULL)
1470 goto onError;
1471 return v;
1472
Benjamin Peterson29060642009-01-31 22:14:21 +00001473 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00001474 return NULL;
1475}
1476
Victor Stinnerae6265f2010-05-15 16:27:27 +00001477PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
1478{
Victor Stinner313a1202010-06-11 23:56:51 +00001479 if (Py_FileSystemDefaultEncoding) {
1480#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
1481 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0)
1482 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1483 PyUnicode_GET_SIZE(unicode),
1484 NULL);
1485#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00001486 return PyUnicode_AsEncodedString(unicode,
1487 Py_FileSystemDefaultEncoding,
1488 "surrogateescape");
Victor Stinner313a1202010-06-11 23:56:51 +00001489 } else
Victor Stinnerae6265f2010-05-15 16:27:27 +00001490 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1491 PyUnicode_GET_SIZE(unicode),
1492 "surrogateescape");
1493}
1494
Guido van Rossumd57fd912000-03-10 22:53:23 +00001495PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
1496 const char *encoding,
1497 const char *errors)
1498{
1499 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00001500 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00001501
Guido van Rossumd57fd912000-03-10 22:53:23 +00001502 if (!PyUnicode_Check(unicode)) {
1503 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001504 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001505 }
Fred Drakee4315f52000-05-09 19:53:39 +00001506
Tim Petersced69f82003-09-16 20:30:58 +00001507 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001508 encoding = PyUnicode_GetDefaultEncoding();
Fred Drakee4315f52000-05-09 19:53:39 +00001509
1510 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00001511 if (normalize_encoding(encoding, lower, sizeof(lower))) {
1512 if (strcmp(lower, "utf-8") == 0)
1513 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
1514 PyUnicode_GET_SIZE(unicode),
1515 errors);
1516 else if ((strcmp(lower, "latin-1") == 0) ||
1517 (strcmp(lower, "iso-8859-1") == 0))
1518 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
1519 PyUnicode_GET_SIZE(unicode),
1520 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001521#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Victor Stinner37296e82010-06-10 13:36:23 +00001522 else if (strcmp(lower, "mbcs") == 0)
1523 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
1524 PyUnicode_GET_SIZE(unicode),
1525 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00001526#endif
Victor Stinner37296e82010-06-10 13:36:23 +00001527 else if (strcmp(lower, "ascii") == 0)
1528 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1529 PyUnicode_GET_SIZE(unicode),
1530 errors);
1531 }
Victor Stinner59e62db2010-05-15 13:14:32 +00001532 /* During bootstrap, we may need to find the encodings
1533 package, to load the file system encoding, and require the
1534 file system encoding in order to load the encodings
1535 package.
Christian Heimes6a27efa2008-10-30 21:48:26 +00001536
Victor Stinner59e62db2010-05-15 13:14:32 +00001537 Break out of this dependency by assuming that the path to
1538 the encodings module is ASCII-only. XXX could try wcstombs
1539 instead, if the file system encoding is the locale's
1540 encoding. */
Victor Stinner37296e82010-06-10 13:36:23 +00001541 if (Py_FileSystemDefaultEncoding &&
Victor Stinner59e62db2010-05-15 13:14:32 +00001542 strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
1543 !PyThreadState_GET()->interp->codecs_initialized)
1544 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
1545 PyUnicode_GET_SIZE(unicode),
1546 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001547
1548 /* Encode via the codec registry */
1549 v = PyCodec_Encode(unicode, encoding, errors);
1550 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001551 return NULL;
1552
1553 /* The normal path */
1554 if (PyBytes_Check(v))
1555 return v;
1556
1557 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001558 if (PyByteArray_Check(v)) {
1559 char msg[100];
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001560 PyObject *b;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001561 PyOS_snprintf(msg, sizeof(msg),
1562 "encoder %s returned buffer instead of bytes",
1563 encoding);
1564 if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001565 Py_DECREF(v);
1566 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001567 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001568
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00001569 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
1570 Py_DECREF(v);
1571 return b;
1572 }
1573
1574 PyErr_Format(PyExc_TypeError,
1575 "encoder did not return a bytes object (type=%.400s)",
1576 Py_TYPE(v)->tp_name);
1577 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001578 return NULL;
1579}
1580
1581PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
1582 const char *encoding,
1583 const char *errors)
1584{
1585 PyObject *v;
1586
1587 if (!PyUnicode_Check(unicode)) {
1588 PyErr_BadArgument();
1589 goto onError;
1590 }
1591
1592 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001593 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001594
1595 /* Encode via the codec registry */
1596 v = PyCodec_Encode(unicode, encoding, errors);
1597 if (v == NULL)
1598 goto onError;
1599 if (!PyUnicode_Check(v)) {
1600 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00001601 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00001602 Py_TYPE(v)->tp_name);
1603 Py_DECREF(v);
1604 goto onError;
1605 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606 return v;
Tim Petersced69f82003-09-16 20:30:58 +00001607
Benjamin Peterson29060642009-01-31 22:14:21 +00001608 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001609 return NULL;
1610}
1611
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001612PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00001613 const char *errors)
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001614{
1615 PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001616 if (v)
1617 return v;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001618 if (errors != NULL)
1619 Py_FatalError("non-NULL encoding in _PyUnicode_AsDefaultEncodedString");
Guido van Rossum98297ee2007-11-06 21:34:58 +00001620 v = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Guido van Rossum06610092007-08-16 21:02:22 +00001621 PyUnicode_GET_SIZE(unicode),
1622 NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001623 if (!v)
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001624 return NULL;
Guido van Rossume7a0d392007-07-12 07:53:00 +00001625 ((PyUnicodeObject *)unicode)->defenc = v;
Marc-André Lemburgbff879c2000-08-03 18:46:08 +00001626 return v;
1627}
1628
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001629PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00001630PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001631 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00001632 return PyUnicode_DecodeFSDefaultAndSize(s, size);
1633}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001634
Christian Heimes5894ba72007-11-04 11:43:14 +00001635PyObject*
1636PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
1637{
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001638 /* During the early bootstrapping process, Py_FileSystemDefaultEncoding
1639 can be undefined. If it is case, decode using UTF-8. The following assumes
1640 that Py_FileSystemDefaultEncoding is set to a built-in encoding during the
1641 bootstrapping process where the codecs aren't ready yet.
1642 */
1643 if (Py_FileSystemDefaultEncoding) {
1644#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Christian Heimes5894ba72007-11-04 11:43:14 +00001645 if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0) {
Victor Stinner313a1202010-06-11 23:56:51 +00001646 return PyUnicode_DecodeMBCS(s, size, NULL);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001647 }
1648#elif defined(__APPLE__)
Christian Heimes5894ba72007-11-04 11:43:14 +00001649 if (strcmp(Py_FileSystemDefaultEncoding, "utf-8") == 0) {
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001650 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001651 }
1652#endif
1653 return PyUnicode_Decode(s, size,
1654 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001655 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001656 }
1657 else {
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00001658 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001659 }
1660}
1661
Martin v. Löwis011e8422009-05-05 04:43:17 +00001662/* Convert the argument to a bytes object, according to the file
Gregory P. Smithcc47d8c2010-02-27 08:33:11 +00001663 system encoding. The addr param must be a PyObject**.
1664 This is designed to be used with "O&" in PyArg_Parse APIs. */
Martin v. Löwis011e8422009-05-05 04:43:17 +00001665
1666int
1667PyUnicode_FSConverter(PyObject* arg, void* addr)
1668{
1669 PyObject *output = NULL;
1670 Py_ssize_t size;
1671 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001672 if (arg == NULL) {
1673 Py_DECREF(*(PyObject**)addr);
1674 return 1;
1675 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00001676 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00001677 output = arg;
1678 Py_INCREF(output);
1679 }
1680 else {
1681 arg = PyUnicode_FromObject(arg);
1682 if (!arg)
1683 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00001684 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001685 Py_DECREF(arg);
1686 if (!output)
1687 return 0;
1688 if (!PyBytes_Check(output)) {
1689 Py_DECREF(output);
1690 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
1691 return 0;
1692 }
1693 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00001694 size = PyBytes_GET_SIZE(output);
1695 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00001696 if (size != strlen(data)) {
1697 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
1698 Py_DECREF(output);
1699 return 0;
1700 }
1701 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00001702 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00001703}
1704
1705
Martin v. Löwis5b222132007-06-10 09:51:05 +00001706char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001707_PyUnicode_AsStringAndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001708{
Christian Heimesf3863112007-11-22 07:46:41 +00001709 PyObject *bytes;
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00001710 if (!PyUnicode_Check(unicode)) {
1711 PyErr_BadArgument();
1712 return NULL;
1713 }
Christian Heimesf3863112007-11-22 07:46:41 +00001714 bytes = _PyUnicode_AsDefaultEncodedString(unicode, NULL);
1715 if (bytes == NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +00001716 return NULL;
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001717 if (psize != NULL)
Christian Heimes72b710a2008-05-26 13:28:38 +00001718 *psize = PyBytes_GET_SIZE(bytes);
1719 return PyBytes_AS_STRING(bytes);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001720}
1721
1722char*
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001723_PyUnicode_AsString(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00001724{
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001725 return _PyUnicode_AsStringAndSize(unicode, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001726}
1727
Guido van Rossumd57fd912000-03-10 22:53:23 +00001728Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
1729{
1730 if (!PyUnicode_Check(unicode)) {
1731 PyErr_BadArgument();
1732 goto onError;
1733 }
1734 return PyUnicode_AS_UNICODE(unicode);
1735
Benjamin Peterson29060642009-01-31 22:14:21 +00001736 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001737 return NULL;
1738}
1739
Martin v. Löwis18e16552006-02-15 17:27:45 +00001740Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001741{
1742 if (!PyUnicode_Check(unicode)) {
1743 PyErr_BadArgument();
1744 goto onError;
1745 }
1746 return PyUnicode_GET_SIZE(unicode);
1747
Benjamin Peterson29060642009-01-31 22:14:21 +00001748 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00001749 return -1;
1750}
1751
Thomas Wouters78890102000-07-22 19:25:51 +00001752const char *PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00001753{
1754 return unicode_default_encoding;
1755}
1756
1757int PyUnicode_SetDefaultEncoding(const char *encoding)
1758{
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001759 if (strcmp(encoding, unicode_default_encoding) != 0) {
1760 PyErr_Format(PyExc_ValueError,
1761 "Can only set default encoding to %s",
1762 unicode_default_encoding);
1763 return -1;
1764 }
Fred Drakee4315f52000-05-09 19:53:39 +00001765 return 0;
Fred Drakee4315f52000-05-09 19:53:39 +00001766}
1767
Victor Stinner554f3f02010-06-16 23:33:54 +00001768/* create or adjust a UnicodeDecodeError */
1769static void
1770make_decode_exception(PyObject **exceptionObject,
1771 const char *encoding,
1772 const char *input, Py_ssize_t length,
1773 Py_ssize_t startpos, Py_ssize_t endpos,
1774 const char *reason)
1775{
1776 if (*exceptionObject == NULL) {
1777 *exceptionObject = PyUnicodeDecodeError_Create(
1778 encoding, input, length, startpos, endpos, reason);
1779 }
1780 else {
1781 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
1782 goto onError;
1783 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
1784 goto onError;
1785 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
1786 goto onError;
1787 }
1788 return;
1789
1790onError:
1791 Py_DECREF(*exceptionObject);
1792 *exceptionObject = NULL;
1793}
1794
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001795/* error handling callback helper:
1796 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00001797 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001798 and adjust various state variables.
1799 return 0 on success, -1 on error
1800*/
1801
1802static
1803int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00001804 const char *encoding, const char *reason,
1805 const char **input, const char **inend, Py_ssize_t *startinpos,
1806 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
1807 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001808{
Benjamin Peterson142957c2008-07-04 19:55:29 +00001809 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001810
1811 PyObject *restuple = NULL;
1812 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001813 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001814 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001815 Py_ssize_t requiredsize;
1816 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001817 Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001818 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001819 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001820 int res = -1;
1821
1822 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001823 *errorHandler = PyCodec_LookupError(errors);
1824 if (*errorHandler == NULL)
1825 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001826 }
1827
Victor Stinner554f3f02010-06-16 23:33:54 +00001828 make_decode_exception(exceptionObject,
1829 encoding,
1830 *input, *inend - *input,
1831 *startinpos, *endinpos,
1832 reason);
1833 if (*exceptionObject == NULL)
1834 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001835
1836 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
1837 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001838 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001839 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001840 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00001841 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001842 }
1843 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00001844 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001845
1846 /* Copy back the bytes variables, which might have been modified by the
1847 callback */
1848 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
1849 if (!inputobj)
1850 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00001851 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001852 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00001853 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001854 *input = PyBytes_AS_STRING(inputobj);
1855 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001856 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00001857 /* we can DECREF safely, as the exception has another reference,
1858 so the object won't go away. */
1859 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00001860
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001861 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001862 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001863 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001864 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
1865 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00001866 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001867
1868 /* need more space? (at least enough for what we
1869 have+the replacement+the rest of the string (starting
1870 at the new input position), so we won't have to check space
1871 when there are no errors in the rest of the string) */
1872 repptr = PyUnicode_AS_UNICODE(repunicode);
1873 repsize = PyUnicode_GET_SIZE(repunicode);
1874 requiredsize = *outpos + repsize + insize-newpos;
1875 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001876 if (requiredsize<2*outsize)
1877 requiredsize = 2*outsize;
1878 if (_PyUnicode_Resize(output, requiredsize) < 0)
1879 goto onError;
1880 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001881 }
1882 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001883 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001884 Py_UNICODE_COPY(*outptr, repptr, repsize);
1885 *outptr += repsize;
1886 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00001887
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001888 /* we made it! */
1889 res = 0;
1890
Benjamin Peterson29060642009-01-31 22:14:21 +00001891 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001892 Py_XDECREF(restuple);
1893 return res;
1894}
1895
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001896/* --- UTF-7 Codec -------------------------------------------------------- */
1897
Antoine Pitrou244651a2009-05-04 18:56:13 +00001898/* See RFC2152 for details. We encode conservatively and decode liberally. */
1899
1900/* Three simple macros defining base-64. */
1901
1902/* Is c a base-64 character? */
1903
1904#define IS_BASE64(c) \
1905 (((c) >= 'A' && (c) <= 'Z') || \
1906 ((c) >= 'a' && (c) <= 'z') || \
1907 ((c) >= '0' && (c) <= '9') || \
1908 (c) == '+' || (c) == '/')
1909
1910/* given that c is a base-64 character, what is its base-64 value? */
1911
1912#define FROM_BASE64(c) \
1913 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
1914 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
1915 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
1916 (c) == '+' ? 62 : 63)
1917
1918/* What is the base-64 character of the bottom 6 bits of n? */
1919
1920#define TO_BASE64(n) \
1921 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
1922
1923/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
1924 * decoded as itself. We are permissive on decoding; the only ASCII
1925 * byte not decoding to itself is the + which begins a base64
1926 * string. */
1927
1928#define DECODE_DIRECT(c) \
1929 ((c) <= 127 && (c) != '+')
1930
1931/* The UTF-7 encoder treats ASCII characters differently according to
1932 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
1933 * the above). See RFC2152. This array identifies these different
1934 * sets:
1935 * 0 : "Set D"
1936 * alphanumeric and '(),-./:?
1937 * 1 : "Set O"
1938 * !"#$%&*;<=>@[]^_`{|}
1939 * 2 : "whitespace"
1940 * ht nl cr sp
1941 * 3 : special (must be base64 encoded)
1942 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
1943 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001944
Tim Petersced69f82003-09-16 20:30:58 +00001945static
Antoine Pitrou244651a2009-05-04 18:56:13 +00001946char utf7_category[128] = {
1947/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
1948 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
1949/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
1950 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1951/* sp ! " # $ % & ' ( ) * + , - . / */
1952 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
1953/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1954 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
1955/* @ A B C D E F G H I J K L M N O */
1956 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1957/* P Q R S T U V W X Y Z [ \ ] ^ _ */
1958 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
1959/* ` a b c d e f g h i j k l m n o */
1960 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1961/* p q r s t u v w x y z { | } ~ del */
1962 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001963};
1964
Antoine Pitrou244651a2009-05-04 18:56:13 +00001965/* ENCODE_DIRECT: this character should be encoded as itself. The
1966 * answer depends on whether we are encoding set O as itself, and also
1967 * on whether we are encoding whitespace as itself. RFC2152 makes it
1968 * clear that the answers to these questions vary between
1969 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00001970
Antoine Pitrou244651a2009-05-04 18:56:13 +00001971#define ENCODE_DIRECT(c, directO, directWS) \
1972 ((c) < 128 && (c) > 0 && \
1973 ((utf7_category[(c)] == 0) || \
1974 (directWS && (utf7_category[(c)] == 2)) || \
1975 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001976
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001977PyObject *PyUnicode_DecodeUTF7(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001978 Py_ssize_t size,
1979 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001980{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001981 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
1982}
1983
Antoine Pitrou244651a2009-05-04 18:56:13 +00001984/* The decoder. The only state we preserve is our read position,
1985 * i.e. how many characters we have consumed. So if we end in the
1986 * middle of a shift sequence we have to back off the read position
1987 * and the output to the beginning of the sequence, otherwise we lose
1988 * all the shift state (seen bits, number of bits seen, high
1989 * surrogate). */
1990
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001991PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00001992 Py_ssize_t size,
1993 const char *errors,
1994 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00001995{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00001996 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 Py_ssize_t startinpos;
1998 Py_ssize_t endinpos;
1999 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002000 const char *e;
2001 PyUnicodeObject *unicode;
2002 Py_UNICODE *p;
2003 const char *errmsg = "";
2004 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002005 Py_UNICODE *shiftOutStart;
2006 unsigned int base64bits = 0;
2007 unsigned long base64buffer = 0;
2008 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002009 PyObject *errorHandler = NULL;
2010 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002011
2012 unicode = _PyUnicode_New(size);
2013 if (!unicode)
2014 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002015 if (size == 0) {
2016 if (consumed)
2017 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002018 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002019 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002020
2021 p = unicode->str;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002022 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002023 e = s + size;
2024
2025 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002026 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00002027 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00002028 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002029
Antoine Pitrou244651a2009-05-04 18:56:13 +00002030 if (inShift) { /* in a base-64 section */
2031 if (IS_BASE64(ch)) { /* consume a base-64 character */
2032 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
2033 base64bits += 6;
2034 s++;
2035 if (base64bits >= 16) {
2036 /* we have enough bits for a UTF-16 value */
2037 Py_UNICODE outCh = (Py_UNICODE)
2038 (base64buffer >> (base64bits-16));
2039 base64bits -= 16;
2040 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
2041 if (surrogate) {
2042 /* expecting a second surrogate */
2043 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2044#ifdef Py_UNICODE_WIDE
2045 *p++ = (((surrogate & 0x3FF)<<10)
2046 | (outCh & 0x3FF)) + 0x10000;
2047#else
2048 *p++ = surrogate;
2049 *p++ = outCh;
2050#endif
2051 surrogate = 0;
2052 }
2053 else {
2054 surrogate = 0;
2055 errmsg = "second surrogate missing";
2056 goto utf7Error;
2057 }
2058 }
2059 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
2060 /* first surrogate */
2061 surrogate = outCh;
2062 }
2063 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
2064 errmsg = "unexpected second surrogate";
2065 goto utf7Error;
2066 }
2067 else {
2068 *p++ = outCh;
2069 }
2070 }
2071 }
2072 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002073 inShift = 0;
2074 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002075 if (surrogate) {
2076 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00002077 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002078 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002079 if (base64bits > 0) { /* left-over bits */
2080 if (base64bits >= 6) {
2081 /* We've seen at least one base-64 character */
2082 errmsg = "partial character in shift sequence";
2083 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002084 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002085 else {
2086 /* Some bits remain; they should be zero */
2087 if (base64buffer != 0) {
2088 errmsg = "non-zero padding bits in shift sequence";
2089 goto utf7Error;
2090 }
2091 }
2092 }
2093 if (ch != '-') {
2094 /* '-' is absorbed; other terminating
2095 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002096 *p++ = ch;
2097 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002098 }
2099 }
2100 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002101 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002102 s++; /* consume '+' */
2103 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002104 s++;
2105 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00002106 }
2107 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002108 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002109 shiftOutStart = p;
2110 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002111 }
2112 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002113 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002114 *p++ = ch;
2115 s++;
2116 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002117 else {
2118 startinpos = s-starts;
2119 s++;
2120 errmsg = "unexpected special character";
2121 goto utf7Error;
2122 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002123 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002124utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002125 outpos = p-PyUnicode_AS_UNICODE(unicode);
2126 endinpos = s-starts;
2127 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00002128 errors, &errorHandler,
2129 "utf7", errmsg,
2130 &starts, &e, &startinpos, &endinpos, &exc, &s,
2131 &unicode, &outpos, &p))
2132 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002133 }
2134
Antoine Pitrou244651a2009-05-04 18:56:13 +00002135 /* end of string */
2136
2137 if (inShift && !consumed) { /* in shift sequence, no more to follow */
2138 /* if we're in an inconsistent state, that's an error */
2139 if (surrogate ||
2140 (base64bits >= 6) ||
2141 (base64bits > 0 && base64buffer != 0)) {
2142 outpos = p-PyUnicode_AS_UNICODE(unicode);
2143 endinpos = size;
2144 if (unicode_decode_call_errorhandler(
2145 errors, &errorHandler,
2146 "utf7", "unterminated shift sequence",
2147 &starts, &e, &startinpos, &endinpos, &exc, &s,
2148 &unicode, &outpos, &p))
2149 goto onError;
2150 if (s < e)
2151 goto restart;
2152 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002153 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002154
2155 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002156 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00002157 if (inShift) {
2158 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002159 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002160 }
2161 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002162 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002163 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00002164 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002165
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002166 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002167 goto onError;
2168
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002169 Py_XDECREF(errorHandler);
2170 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002171 return (PyObject *)unicode;
2172
Benjamin Peterson29060642009-01-31 22:14:21 +00002173 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002174 Py_XDECREF(errorHandler);
2175 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002176 Py_DECREF(unicode);
2177 return NULL;
2178}
2179
2180
2181PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002182 Py_ssize_t size,
Antoine Pitrou244651a2009-05-04 18:56:13 +00002183 int base64SetO,
2184 int base64WhiteSpace,
Benjamin Peterson29060642009-01-31 22:14:21 +00002185 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002186{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002187 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002188 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002189 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002190 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002191 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002192 unsigned int base64bits = 0;
2193 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002194 char * out;
2195 char * start;
2196
2197 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002198 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002199
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00002200 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002201 return PyErr_NoMemory();
2202
Antoine Pitrou244651a2009-05-04 18:56:13 +00002203 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002204 if (v == NULL)
2205 return NULL;
2206
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002207 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002208 for (;i < size; ++i) {
2209 Py_UNICODE ch = s[i];
2210
Antoine Pitrou244651a2009-05-04 18:56:13 +00002211 if (inShift) {
2212 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2213 /* shifting out */
2214 if (base64bits) { /* output remaining bits */
2215 *out++ = TO_BASE64(base64buffer << (6-base64bits));
2216 base64buffer = 0;
2217 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002218 }
2219 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00002220 /* Characters not in the BASE64 set implicitly unshift the sequence
2221 so no '-' is required, except if the character is itself a '-' */
2222 if (IS_BASE64(ch) || ch == '-') {
2223 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002224 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002225 *out++ = (char) ch;
2226 }
2227 else {
2228 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00002229 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002230 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002231 else { /* not in a shift sequence */
2232 if (ch == '+') {
2233 *out++ = '+';
2234 *out++ = '-';
2235 }
2236 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
2237 *out++ = (char) ch;
2238 }
2239 else {
2240 *out++ = '+';
2241 inShift = 1;
2242 goto encode_char;
2243 }
2244 }
2245 continue;
2246encode_char:
2247#ifdef Py_UNICODE_WIDE
2248 if (ch >= 0x10000) {
2249 /* code first surrogate */
2250 base64bits += 16;
2251 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
2252 while (base64bits >= 6) {
2253 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2254 base64bits -= 6;
2255 }
2256 /* prepare second surrogate */
2257 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
2258 }
2259#endif
2260 base64bits += 16;
2261 base64buffer = (base64buffer << 16) | ch;
2262 while (base64bits >= 6) {
2263 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
2264 base64bits -= 6;
2265 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00002266 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00002267 if (base64bits)
2268 *out++= TO_BASE64(base64buffer << (6-base64bits) );
2269 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002270 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002271 if (_PyBytes_Resize(&v, out - start) < 0)
2272 return NULL;
2273 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002274}
2275
Antoine Pitrou244651a2009-05-04 18:56:13 +00002276#undef IS_BASE64
2277#undef FROM_BASE64
2278#undef TO_BASE64
2279#undef DECODE_DIRECT
2280#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002281
Guido van Rossumd57fd912000-03-10 22:53:23 +00002282/* --- UTF-8 Codec -------------------------------------------------------- */
2283
Tim Petersced69f82003-09-16 20:30:58 +00002284static
Guido van Rossumd57fd912000-03-10 22:53:23 +00002285char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00002286 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
2287 illegal prefix. See RFC 3629 for details */
2288 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
2289 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2290 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00002291 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2292 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2293 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2294 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00002295 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
2296 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002297 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2298 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00002299 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
2300 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
2301 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
2302 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
2303 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304};
2305
Guido van Rossumd57fd912000-03-10 22:53:23 +00002306PyObject *PyUnicode_DecodeUTF8(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002307 Py_ssize_t size,
2308 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002309{
Walter Dörwald69652032004-09-07 20:24:22 +00002310 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
2311}
2312
Antoine Pitrouab868312009-01-10 15:40:25 +00002313/* Mask to check or force alignment of a pointer to C 'long' boundaries */
2314#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
2315
2316/* Mask to quickly check whether a C 'long' contains a
2317 non-ASCII, UTF8-encoded char. */
2318#if (SIZEOF_LONG == 8)
2319# define ASCII_CHAR_MASK 0x8080808080808080L
2320#elif (SIZEOF_LONG == 4)
2321# define ASCII_CHAR_MASK 0x80808080L
2322#else
2323# error C 'long' size should be either 4 or 8!
2324#endif
2325
Walter Dörwald69652032004-09-07 20:24:22 +00002326PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002327 Py_ssize_t size,
2328 const char *errors,
2329 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00002330{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002331 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002332 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00002333 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002334 Py_ssize_t startinpos;
2335 Py_ssize_t endinpos;
2336 Py_ssize_t outpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00002337 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002338 PyUnicodeObject *unicode;
2339 Py_UNICODE *p;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002340 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002341 PyObject *errorHandler = NULL;
2342 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002343
2344 /* Note: size will always be longer than the resulting Unicode
2345 character count */
2346 unicode = _PyUnicode_New(size);
2347 if (!unicode)
2348 return NULL;
Walter Dörwald69652032004-09-07 20:24:22 +00002349 if (size == 0) {
2350 if (consumed)
2351 *consumed = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002352 return (PyObject *)unicode;
Walter Dörwald69652032004-09-07 20:24:22 +00002353 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002354
2355 /* Unpack UTF-8 encoded data */
2356 p = unicode->str;
2357 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00002358 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002359
2360 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002361 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002362
2363 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00002364 /* Fast path for runs of ASCII characters. Given that common UTF-8
2365 input will consist of an overwhelming majority of ASCII
2366 characters, we try to optimize for this case by checking
2367 as many characters as a C 'long' can contain.
2368 First, check if we can do an aligned read, as most CPUs have
2369 a penalty for unaligned reads.
2370 */
2371 if (!((size_t) s & LONG_PTR_MASK)) {
2372 /* Help register allocation */
2373 register const char *_s = s;
2374 register Py_UNICODE *_p = p;
2375 while (_s < aligned_end) {
2376 /* Read a whole long at a time (either 4 or 8 bytes),
2377 and do a fast unrolled copy if it only contains ASCII
2378 characters. */
2379 unsigned long data = *(unsigned long *) _s;
2380 if (data & ASCII_CHAR_MASK)
2381 break;
2382 _p[0] = (unsigned char) _s[0];
2383 _p[1] = (unsigned char) _s[1];
2384 _p[2] = (unsigned char) _s[2];
2385 _p[3] = (unsigned char) _s[3];
2386#if (SIZEOF_LONG == 8)
2387 _p[4] = (unsigned char) _s[4];
2388 _p[5] = (unsigned char) _s[5];
2389 _p[6] = (unsigned char) _s[6];
2390 _p[7] = (unsigned char) _s[7];
2391#endif
2392 _s += SIZEOF_LONG;
2393 _p += SIZEOF_LONG;
2394 }
2395 s = _s;
2396 p = _p;
2397 if (s == e)
2398 break;
2399 ch = (unsigned char)*s;
2400 }
2401 }
2402
2403 if (ch < 0x80) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002404 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002405 s++;
2406 continue;
2407 }
2408
2409 n = utf8_code_length[ch];
2410
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002411 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002412 if (consumed)
2413 break;
2414 else {
2415 errmsg = "unexpected end of data";
2416 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002417 endinpos = startinpos+1;
2418 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
2419 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002420 goto utf8Error;
2421 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002422 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002423
2424 switch (n) {
2425
2426 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00002427 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002428 startinpos = s-starts;
2429 endinpos = startinpos+1;
2430 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002431
2432 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002433 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00002434 startinpos = s-starts;
2435 endinpos = startinpos+1;
2436 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002437
2438 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00002439 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00002440 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002441 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002442 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00002443 goto utf8Error;
2444 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002445 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002446 assert ((ch > 0x007F) && (ch <= 0x07FF));
2447 *p++ = (Py_UNICODE)ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002448 break;
2449
2450 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00002451 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
2452 will result in surrogates in range d800-dfff. Surrogates are
2453 not valid UTF-8 so they are rejected.
2454 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
2455 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00002456 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002457 (s[2] & 0xc0) != 0x80 ||
2458 ((unsigned char)s[0] == 0xE0 &&
2459 (unsigned char)s[1] < 0xA0) ||
2460 ((unsigned char)s[0] == 0xED &&
2461 (unsigned char)s[1] > 0x9F)) {
2462 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002463 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002464 endinpos = startinpos + 1;
2465
2466 /* if s[1] first two bits are 1 and 0, then the invalid
2467 continuation byte is s[2], so increment endinpos by 1,
2468 if not, s[1] is invalid and endinpos doesn't need to
2469 be incremented. */
2470 if ((s[1] & 0xC0) == 0x80)
2471 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00002472 goto utf8Error;
2473 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002474 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00002475 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
2476 *p++ = (Py_UNICODE)ch;
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002477 break;
2478
2479 case 4:
2480 if ((s[1] & 0xc0) != 0x80 ||
2481 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00002482 (s[3] & 0xc0) != 0x80 ||
2483 ((unsigned char)s[0] == 0xF0 &&
2484 (unsigned char)s[1] < 0x90) ||
2485 ((unsigned char)s[0] == 0xF4 &&
2486 (unsigned char)s[1] > 0x8F)) {
2487 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00002488 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00002489 endinpos = startinpos + 1;
2490 if ((s[1] & 0xC0) == 0x80) {
2491 endinpos++;
2492 if ((s[2] & 0xC0) == 0x80)
2493 endinpos++;
2494 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002495 goto utf8Error;
2496 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002497 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00002498 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
2499 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
2500
Fredrik Lundh8f455852001-06-27 18:59:43 +00002501#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002502 *p++ = (Py_UNICODE)ch;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002503#else
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002504 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00002505
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002506 /* translate from 10000..10FFFF to 0..FFFF */
2507 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00002508
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002509 /* high surrogate = top 10 bits added to D800 */
2510 *p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
Tim Petersced69f82003-09-16 20:30:58 +00002511
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002512 /* low surrogate = bottom 10 bits added to DC00 */
Fredrik Lundh45714e92001-06-26 16:39:36 +00002513 *p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00002514#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00002515 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002516 }
2517 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00002518 continue;
Tim Petersced69f82003-09-16 20:30:58 +00002519
Benjamin Peterson29060642009-01-31 22:14:21 +00002520 utf8Error:
2521 outpos = p-PyUnicode_AS_UNICODE(unicode);
2522 if (unicode_decode_call_errorhandler(
2523 errors, &errorHandler,
2524 "utf8", errmsg,
2525 &starts, &e, &startinpos, &endinpos, &exc, &s,
2526 &unicode, &outpos, &p))
2527 goto onError;
2528 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002529 }
Walter Dörwald69652032004-09-07 20:24:22 +00002530 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002531 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002532
2533 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00002534 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002535 goto onError;
2536
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002537 Py_XDECREF(errorHandler);
2538 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002539 return (PyObject *)unicode;
2540
Benjamin Peterson29060642009-01-31 22:14:21 +00002541 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002542 Py_XDECREF(errorHandler);
2543 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002544 Py_DECREF(unicode);
2545 return NULL;
2546}
2547
Antoine Pitrouab868312009-01-10 15:40:25 +00002548#undef ASCII_CHAR_MASK
2549
2550
Tim Peters602f7402002-04-27 18:03:26 +00002551/* Allocation strategy: if the string is short, convert into a stack buffer
2552 and allocate exactly as much space needed at the end. Else allocate the
2553 maximum possible needed (4 result bytes per Unicode character), and return
2554 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002555*/
Tim Peters7e3d9612002-04-21 03:26:37 +00002556PyObject *
2557PyUnicode_EncodeUTF8(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002558 Py_ssize_t size,
2559 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002560{
Tim Peters602f7402002-04-27 18:03:26 +00002561#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00002562
Guido van Rossum98297ee2007-11-06 21:34:58 +00002563 Py_ssize_t i; /* index into s of next input byte */
2564 PyObject *result; /* result string object */
2565 char *p; /* next free byte in output buffer */
2566 Py_ssize_t nallocated; /* number of result bytes allocated */
2567 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00002568 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002569 PyObject *errorHandler = NULL;
2570 PyObject *exc = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002571
Tim Peters602f7402002-04-27 18:03:26 +00002572 assert(s != NULL);
2573 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002574
Tim Peters602f7402002-04-27 18:03:26 +00002575 if (size <= MAX_SHORT_UNICHARS) {
2576 /* Write into the stack buffer; nallocated can't overflow.
2577 * At the end, we'll allocate exactly as much heap space as it
2578 * turns out we need.
2579 */
2580 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002581 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00002582 p = stackbuf;
2583 }
2584 else {
2585 /* Overallocate on the heap, and give the excess back at the end. */
2586 nallocated = size * 4;
2587 if (nallocated / 4 != size) /* overflow! */
2588 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00002589 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002590 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00002591 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00002592 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002593 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002594
Tim Peters602f7402002-04-27 18:03:26 +00002595 for (i = 0; i < size;) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00002596 Py_UCS4 ch = s[i++];
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002597
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002598 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00002599 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002600 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002601
Guido van Rossumd57fd912000-03-10 22:53:23 +00002602 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00002603 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00002604 *p++ = (char)(0xc0 | (ch >> 6));
2605 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002606 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002607#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002608 /* Special case: check for high and low surrogate */
2609 if (ch <= 0xDBFF && i != size && 0xDC00 <= s[i] && s[i] <= 0xDFFF) {
2610 Py_UCS4 ch2 = s[i];
2611 /* Combine the two surrogates to form a UCS4 value */
2612 ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
2613 i++;
2614
2615 /* Encode UCS4 Unicode ordinals */
2616 *p++ = (char)(0xf0 | (ch >> 18));
2617 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
Tim Peters602f7402002-04-27 18:03:26 +00002618 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2619 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00002620 } else {
Victor Stinner445a6232010-04-22 20:01:57 +00002621#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002622 Py_ssize_t newpos;
2623 PyObject *rep;
2624 Py_ssize_t repsize, k;
2625 rep = unicode_encode_call_errorhandler
2626 (errors, &errorHandler, "utf-8", "surrogates not allowed",
2627 s, size, &exc, i-1, i, &newpos);
2628 if (!rep)
2629 goto error;
2630
2631 if (PyBytes_Check(rep))
2632 repsize = PyBytes_GET_SIZE(rep);
2633 else
2634 repsize = PyUnicode_GET_SIZE(rep);
2635
2636 if (repsize > 4) {
2637 Py_ssize_t offset;
2638
2639 if (result == NULL)
2640 offset = p - stackbuf;
2641 else
2642 offset = p - PyBytes_AS_STRING(result);
2643
2644 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
2645 /* integer overflow */
2646 PyErr_NoMemory();
2647 goto error;
2648 }
2649 nallocated += repsize - 4;
2650 if (result != NULL) {
2651 if (_PyBytes_Resize(&result, nallocated) < 0)
2652 goto error;
2653 } else {
2654 result = PyBytes_FromStringAndSize(NULL, nallocated);
2655 if (result == NULL)
2656 goto error;
2657 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
2658 }
2659 p = PyBytes_AS_STRING(result) + offset;
2660 }
2661
2662 if (PyBytes_Check(rep)) {
2663 char *prep = PyBytes_AS_STRING(rep);
2664 for(k = repsize; k > 0; k--)
2665 *p++ = *prep++;
2666 } else /* rep is unicode */ {
2667 Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
2668 Py_UNICODE c;
2669
2670 for(k=0; k<repsize; k++) {
2671 c = prep[k];
2672 if (0x80 <= c) {
2673 raise_encode_exception(&exc, "utf-8", s, size,
2674 i-1, i, "surrogates not allowed");
2675 goto error;
2676 }
2677 *p++ = (char)prep[k];
2678 }
2679 }
2680 Py_DECREF(rep);
Victor Stinner445a6232010-04-22 20:01:57 +00002681#ifndef Py_UNICODE_WIDE
Victor Stinner31be90b2010-04-22 19:38:16 +00002682 }
Victor Stinner445a6232010-04-22 20:01:57 +00002683#endif
Victor Stinner31be90b2010-04-22 19:38:16 +00002684 } else if (ch < 0x10000) {
2685 *p++ = (char)(0xe0 | (ch >> 12));
2686 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2687 *p++ = (char)(0x80 | (ch & 0x3f));
2688 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00002689 /* Encode UCS4 Unicode ordinals */
2690 *p++ = (char)(0xf0 | (ch >> 18));
2691 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
2692 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
2693 *p++ = (char)(0x80 | (ch & 0x3f));
2694 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002695 }
Tim Peters0eca65c2002-04-21 17:28:06 +00002696
Guido van Rossum98297ee2007-11-06 21:34:58 +00002697 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00002698 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002699 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00002700 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002701 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002702 }
2703 else {
Christian Heimesf3863112007-11-22 07:46:41 +00002704 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00002705 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00002706 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00002707 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00002708 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002709 Py_XDECREF(errorHandler);
2710 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002711 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00002712 error:
2713 Py_XDECREF(errorHandler);
2714 Py_XDECREF(exc);
2715 Py_XDECREF(result);
2716 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00002717
Tim Peters602f7402002-04-27 18:03:26 +00002718#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00002719}
2720
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
2722{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002723 if (!PyUnicode_Check(unicode)) {
2724 PyErr_BadArgument();
2725 return NULL;
2726 }
Barry Warsaw2dd4abf2000-08-18 06:58:15 +00002727 return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00002728 PyUnicode_GET_SIZE(unicode),
2729 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002730}
2731
Walter Dörwald41980ca2007-08-16 21:55:45 +00002732/* --- UTF-32 Codec ------------------------------------------------------- */
2733
2734PyObject *
2735PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002736 Py_ssize_t size,
2737 const char *errors,
2738 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002739{
2740 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
2741}
2742
2743PyObject *
2744PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002745 Py_ssize_t size,
2746 const char *errors,
2747 int *byteorder,
2748 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002749{
2750 const char *starts = s;
2751 Py_ssize_t startinpos;
2752 Py_ssize_t endinpos;
2753 Py_ssize_t outpos;
2754 PyUnicodeObject *unicode;
2755 Py_UNICODE *p;
2756#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00002757 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00002758 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002759#else
2760 const int pairs = 0;
2761#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00002762 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002763 int bo = 0; /* assume native ordering by default */
2764 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00002765 /* Offsets from q for retrieving bytes in the right order. */
2766#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2767 int iorder[] = {0, 1, 2, 3};
2768#else
2769 int iorder[] = {3, 2, 1, 0};
2770#endif
2771 PyObject *errorHandler = NULL;
2772 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00002773
Walter Dörwald41980ca2007-08-16 21:55:45 +00002774 q = (unsigned char *)s;
2775 e = q + size;
2776
2777 if (byteorder)
2778 bo = *byteorder;
2779
2780 /* Check for BOM marks (U+FEFF) in the input and adjust current
2781 byte order setting accordingly. In native mode, the leading BOM
2782 mark is skipped, in all other modes, it is copied to the output
2783 stream as-is (giving a ZWNBSP character). */
2784 if (bo == 0) {
2785 if (size >= 4) {
2786 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002788#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00002789 if (bom == 0x0000FEFF) {
2790 q += 4;
2791 bo = -1;
2792 }
2793 else if (bom == 0xFFFE0000) {
2794 q += 4;
2795 bo = 1;
2796 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002797#else
Benjamin Peterson29060642009-01-31 22:14:21 +00002798 if (bom == 0x0000FEFF) {
2799 q += 4;
2800 bo = 1;
2801 }
2802 else if (bom == 0xFFFE0000) {
2803 q += 4;
2804 bo = -1;
2805 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002806#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002807 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002808 }
2809
2810 if (bo == -1) {
2811 /* force LE */
2812 iorder[0] = 0;
2813 iorder[1] = 1;
2814 iorder[2] = 2;
2815 iorder[3] = 3;
2816 }
2817 else if (bo == 1) {
2818 /* force BE */
2819 iorder[0] = 3;
2820 iorder[1] = 2;
2821 iorder[2] = 1;
2822 iorder[3] = 0;
2823 }
2824
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00002825 /* On narrow builds we split characters outside the BMP into two
2826 codepoints => count how much extra space we need. */
2827#ifndef Py_UNICODE_WIDE
2828 for (qq = q; qq < e; qq += 4)
2829 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
2830 pairs++;
2831#endif
2832
2833 /* This might be one to much, because of a BOM */
2834 unicode = _PyUnicode_New((size+3)/4+pairs);
2835 if (!unicode)
2836 return NULL;
2837 if (size == 0)
2838 return (PyObject *)unicode;
2839
2840 /* Unpack UTF-32 encoded data */
2841 p = unicode->str;
2842
Walter Dörwald41980ca2007-08-16 21:55:45 +00002843 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002844 Py_UCS4 ch;
2845 /* remaining bytes at the end? (size should be divisible by 4) */
2846 if (e-q<4) {
2847 if (consumed)
2848 break;
2849 errmsg = "truncated data";
2850 startinpos = ((const char *)q)-starts;
2851 endinpos = ((const char *)e)-starts;
2852 goto utf32Error;
2853 /* The remaining input chars are ignored if the callback
2854 chooses to skip the input */
2855 }
2856 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
2857 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00002858
Benjamin Peterson29060642009-01-31 22:14:21 +00002859 if (ch >= 0x110000)
2860 {
2861 errmsg = "codepoint not in range(0x110000)";
2862 startinpos = ((const char *)q)-starts;
2863 endinpos = startinpos+4;
2864 goto utf32Error;
2865 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002866#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002867 if (ch >= 0x10000)
2868 {
2869 *p++ = 0xD800 | ((ch-0x10000) >> 10);
2870 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
2871 }
2872 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00002873#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00002874 *p++ = ch;
2875 q += 4;
2876 continue;
2877 utf32Error:
2878 outpos = p-PyUnicode_AS_UNICODE(unicode);
2879 if (unicode_decode_call_errorhandler(
2880 errors, &errorHandler,
2881 "utf32", errmsg,
2882 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
2883 &unicode, &outpos, &p))
2884 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002885 }
2886
2887 if (byteorder)
2888 *byteorder = bo;
2889
2890 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00002891 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002892
2893 /* Adjust length */
2894 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
2895 goto onError;
2896
2897 Py_XDECREF(errorHandler);
2898 Py_XDECREF(exc);
2899 return (PyObject *)unicode;
2900
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00002902 Py_DECREF(unicode);
2903 Py_XDECREF(errorHandler);
2904 Py_XDECREF(exc);
2905 return NULL;
2906}
2907
2908PyObject *
2909PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00002910 Py_ssize_t size,
2911 const char *errors,
2912 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00002913{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002914 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002915 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002916 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002917#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002918 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002919#else
2920 const int pairs = 0;
2921#endif
2922 /* Offsets from p for storing byte pairs in the right order. */
2923#ifdef BYTEORDER_IS_LITTLE_ENDIAN
2924 int iorder[] = {0, 1, 2, 3};
2925#else
2926 int iorder[] = {3, 2, 1, 0};
2927#endif
2928
Benjamin Peterson29060642009-01-31 22:14:21 +00002929#define STORECHAR(CH) \
2930 do { \
2931 p[iorder[3]] = ((CH) >> 24) & 0xff; \
2932 p[iorder[2]] = ((CH) >> 16) & 0xff; \
2933 p[iorder[1]] = ((CH) >> 8) & 0xff; \
2934 p[iorder[0]] = (CH) & 0xff; \
2935 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00002936 } while(0)
2937
2938 /* In narrow builds we can output surrogate pairs as one codepoint,
2939 so we need less space. */
2940#ifndef Py_UNICODE_WIDE
2941 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00002942 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
2943 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
2944 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002945#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00002946 nsize = (size - pairs + (byteorder == 0));
2947 bytesize = nsize * 4;
2948 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00002949 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002950 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002951 if (v == NULL)
2952 return NULL;
2953
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002954 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002955 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002956 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00002957 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002958 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002959
2960 if (byteorder == -1) {
2961 /* force LE */
2962 iorder[0] = 0;
2963 iorder[1] = 1;
2964 iorder[2] = 2;
2965 iorder[3] = 3;
2966 }
2967 else if (byteorder == 1) {
2968 /* force BE */
2969 iorder[0] = 3;
2970 iorder[1] = 2;
2971 iorder[2] = 1;
2972 iorder[3] = 0;
2973 }
2974
2975 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002976 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002977#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00002978 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
2979 Py_UCS4 ch2 = *s;
2980 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
2981 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
2982 s++;
2983 size--;
2984 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002985 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00002986#endif
2987 STORECHAR(ch);
2988 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002989
2990 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00002991 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00002992#undef STORECHAR
2993}
2994
2995PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
2996{
2997 if (!PyUnicode_Check(unicode)) {
2998 PyErr_BadArgument();
2999 return NULL;
3000 }
3001 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003002 PyUnicode_GET_SIZE(unicode),
3003 NULL,
3004 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00003005}
3006
Guido van Rossumd57fd912000-03-10 22:53:23 +00003007/* --- UTF-16 Codec ------------------------------------------------------- */
3008
Tim Peters772747b2001-08-09 22:21:55 +00003009PyObject *
3010PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003011 Py_ssize_t size,
3012 const char *errors,
3013 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014{
Walter Dörwald69652032004-09-07 20:24:22 +00003015 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
3016}
3017
Antoine Pitrouab868312009-01-10 15:40:25 +00003018/* Two masks for fast checking of whether a C 'long' may contain
3019 UTF16-encoded surrogate characters. This is an efficient heuristic,
3020 assuming that non-surrogate characters with a code point >= 0x8000 are
3021 rare in most input.
3022 FAST_CHAR_MASK is used when the input is in native byte ordering,
3023 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00003024*/
Antoine Pitrouab868312009-01-10 15:40:25 +00003025#if (SIZEOF_LONG == 8)
3026# define FAST_CHAR_MASK 0x8000800080008000L
3027# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
3028#elif (SIZEOF_LONG == 4)
3029# define FAST_CHAR_MASK 0x80008000L
3030# define SWAPPED_FAST_CHAR_MASK 0x00800080L
3031#else
3032# error C 'long' size should be either 4 or 8!
3033#endif
3034
Walter Dörwald69652032004-09-07 20:24:22 +00003035PyObject *
3036PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003037 Py_ssize_t size,
3038 const char *errors,
3039 int *byteorder,
3040 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003041{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003042 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003043 Py_ssize_t startinpos;
3044 Py_ssize_t endinpos;
3045 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 PyUnicodeObject *unicode;
3047 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00003048 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00003049 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00003050 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003051 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00003052 /* Offsets from q for retrieving byte pairs in the right order. */
3053#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3054 int ihi = 1, ilo = 0;
3055#else
3056 int ihi = 0, ilo = 1;
3057#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003058 PyObject *errorHandler = NULL;
3059 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060
3061 /* Note: size will always be longer than the resulting Unicode
3062 character count */
3063 unicode = _PyUnicode_New(size);
3064 if (!unicode)
3065 return NULL;
3066 if (size == 0)
3067 return (PyObject *)unicode;
3068
3069 /* Unpack UTF-16 encoded data */
3070 p = unicode->str;
Tim Peters772747b2001-08-09 22:21:55 +00003071 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00003072 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003073
3074 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00003075 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003076
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003077 /* Check for BOM marks (U+FEFF) in the input and adjust current
3078 byte order setting accordingly. In native mode, the leading BOM
3079 mark is skipped, in all other modes, it is copied to the output
3080 stream as-is (giving a ZWNBSP character). */
3081 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00003082 if (size >= 2) {
3083 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003084#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 if (bom == 0xFEFF) {
3086 q += 2;
3087 bo = -1;
3088 }
3089 else if (bom == 0xFFFE) {
3090 q += 2;
3091 bo = 1;
3092 }
Tim Petersced69f82003-09-16 20:30:58 +00003093#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003094 if (bom == 0xFEFF) {
3095 q += 2;
3096 bo = 1;
3097 }
3098 else if (bom == 0xFFFE) {
3099 q += 2;
3100 bo = -1;
3101 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003102#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003103 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00003104 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003105
Tim Peters772747b2001-08-09 22:21:55 +00003106 if (bo == -1) {
3107 /* force LE */
3108 ihi = 1;
3109 ilo = 0;
3110 }
3111 else if (bo == 1) {
3112 /* force BE */
3113 ihi = 0;
3114 ilo = 1;
3115 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003116#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3117 native_ordering = ilo < ihi;
3118#else
3119 native_ordering = ilo > ihi;
3120#endif
Tim Peters772747b2001-08-09 22:21:55 +00003121
Antoine Pitrouab868312009-01-10 15:40:25 +00003122 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00003123 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003124 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00003125 /* First check for possible aligned read of a C 'long'. Unaligned
3126 reads are more expensive, better to defer to another iteration. */
3127 if (!((size_t) q & LONG_PTR_MASK)) {
3128 /* Fast path for runs of non-surrogate chars. */
3129 register const unsigned char *_q = q;
3130 Py_UNICODE *_p = p;
3131 if (native_ordering) {
3132 /* Native ordering is simple: as long as the input cannot
3133 possibly contain a surrogate char, do an unrolled copy
3134 of several 16-bit code points to the target object.
3135 The non-surrogate check is done on several input bytes
3136 at a time (as many as a C 'long' can contain). */
3137 while (_q < aligned_end) {
3138 unsigned long data = * (unsigned long *) _q;
3139 if (data & FAST_CHAR_MASK)
3140 break;
3141 _p[0] = ((unsigned short *) _q)[0];
3142 _p[1] = ((unsigned short *) _q)[1];
3143#if (SIZEOF_LONG == 8)
3144 _p[2] = ((unsigned short *) _q)[2];
3145 _p[3] = ((unsigned short *) _q)[3];
3146#endif
3147 _q += SIZEOF_LONG;
3148 _p += SIZEOF_LONG / 2;
3149 }
3150 }
3151 else {
3152 /* Byteswapped ordering is similar, but we must decompose
3153 the copy bytewise, and take care of zero'ing out the
3154 upper bytes if the target object is in 32-bit units
3155 (that is, in UCS-4 builds). */
3156 while (_q < aligned_end) {
3157 unsigned long data = * (unsigned long *) _q;
3158 if (data & SWAPPED_FAST_CHAR_MASK)
3159 break;
3160 /* Zero upper bytes in UCS-4 builds */
3161#if (Py_UNICODE_SIZE > 2)
3162 _p[0] = 0;
3163 _p[1] = 0;
3164#if (SIZEOF_LONG == 8)
3165 _p[2] = 0;
3166 _p[3] = 0;
3167#endif
3168#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003169 /* Issue #4916; UCS-4 builds on big endian machines must
3170 fill the two last bytes of each 4-byte unit. */
3171#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
3172# define OFF 2
3173#else
3174# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00003175#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00003176 ((unsigned char *) _p)[OFF + 1] = _q[0];
3177 ((unsigned char *) _p)[OFF + 0] = _q[1];
3178 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
3179 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
3180#if (SIZEOF_LONG == 8)
3181 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
3182 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
3183 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
3184 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
3185#endif
3186#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00003187 _q += SIZEOF_LONG;
3188 _p += SIZEOF_LONG / 2;
3189 }
3190 }
3191 p = _p;
3192 q = _q;
3193 if (q >= e)
3194 break;
3195 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003197
Benjamin Peterson14339b62009-01-31 16:36:08 +00003198 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00003199
3200 if (ch < 0xD800 || ch > 0xDFFF) {
3201 *p++ = ch;
3202 continue;
3203 }
3204
3205 /* UTF-16 code pair: */
3206 if (q > e) {
3207 errmsg = "unexpected end of data";
3208 startinpos = (((const char *)q) - 2) - starts;
3209 endinpos = ((const char *)e) + 1 - starts;
3210 goto utf16Error;
3211 }
3212 if (0xD800 <= ch && ch <= 0xDBFF) {
3213 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
3214 q += 2;
3215 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00003216#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003217 *p++ = ch;
3218 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003219#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003220 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003221#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003222 continue;
3223 }
3224 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003225 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00003226 startinpos = (((const char *)q)-4)-starts;
3227 endinpos = startinpos+2;
3228 goto utf16Error;
3229 }
3230
Benjamin Peterson14339b62009-01-31 16:36:08 +00003231 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003232 errmsg = "illegal encoding";
3233 startinpos = (((const char *)q)-2)-starts;
3234 endinpos = startinpos+2;
3235 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003236
Benjamin Peterson29060642009-01-31 22:14:21 +00003237 utf16Error:
3238 outpos = p - PyUnicode_AS_UNICODE(unicode);
3239 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00003240 errors,
3241 &errorHandler,
3242 "utf16", errmsg,
3243 &starts,
3244 (const char **)&e,
3245 &startinpos,
3246 &endinpos,
3247 &exc,
3248 (const char **)&q,
3249 &unicode,
3250 &outpos,
3251 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00003252 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003253 }
Antoine Pitrouab868312009-01-10 15:40:25 +00003254 /* remaining byte at the end? (size should be even) */
3255 if (e == q) {
3256 if (!consumed) {
3257 errmsg = "truncated data";
3258 startinpos = ((const char *)q) - starts;
3259 endinpos = ((const char *)e) + 1 - starts;
3260 outpos = p - PyUnicode_AS_UNICODE(unicode);
3261 if (unicode_decode_call_errorhandler(
3262 errors,
3263 &errorHandler,
3264 "utf16", errmsg,
3265 &starts,
3266 (const char **)&e,
3267 &startinpos,
3268 &endinpos,
3269 &exc,
3270 (const char **)&q,
3271 &unicode,
3272 &outpos,
3273 &p))
3274 goto onError;
3275 /* The remaining input chars are ignored if the callback
3276 chooses to skip the input */
3277 }
3278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003279
3280 if (byteorder)
3281 *byteorder = bo;
3282
Walter Dörwald69652032004-09-07 20:24:22 +00003283 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003284 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00003285
Guido van Rossumd57fd912000-03-10 22:53:23 +00003286 /* Adjust length */
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003287 if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003288 goto onError;
3289
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003290 Py_XDECREF(errorHandler);
3291 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292 return (PyObject *)unicode;
3293
Benjamin Peterson29060642009-01-31 22:14:21 +00003294 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003295 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003296 Py_XDECREF(errorHandler);
3297 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003298 return NULL;
3299}
3300
Antoine Pitrouab868312009-01-10 15:40:25 +00003301#undef FAST_CHAR_MASK
3302#undef SWAPPED_FAST_CHAR_MASK
3303
Tim Peters772747b2001-08-09 22:21:55 +00003304PyObject *
3305PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003306 Py_ssize_t size,
3307 const char *errors,
3308 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003309{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003310 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00003311 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003312 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003313#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003314 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003315#else
3316 const int pairs = 0;
3317#endif
Tim Peters772747b2001-08-09 22:21:55 +00003318 /* Offsets from p for storing byte pairs in the right order. */
3319#ifdef BYTEORDER_IS_LITTLE_ENDIAN
3320 int ihi = 1, ilo = 0;
3321#else
3322 int ihi = 0, ilo = 1;
3323#endif
3324
Benjamin Peterson29060642009-01-31 22:14:21 +00003325#define STORECHAR(CH) \
3326 do { \
3327 p[ihi] = ((CH) >> 8) & 0xff; \
3328 p[ilo] = (CH) & 0xff; \
3329 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00003330 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003331
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003332#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003333 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00003334 if (s[i] >= 0x10000)
3335 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003336#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003337 /* 2 * (size + pairs + (byteorder == 0)) */
3338 if (size > PY_SSIZE_T_MAX ||
3339 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00003340 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003341 nsize = size + pairs + (byteorder == 0);
3342 bytesize = nsize * 2;
3343 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003344 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003345 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003346 if (v == NULL)
3347 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003348
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003349 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003350 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003351 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003352 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00003353 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00003354
3355 if (byteorder == -1) {
3356 /* force LE */
3357 ihi = 1;
3358 ilo = 0;
3359 }
3360 else if (byteorder == 1) {
3361 /* force BE */
3362 ihi = 0;
3363 ilo = 1;
3364 }
3365
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003366 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003367 Py_UNICODE ch = *s++;
3368 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003369#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003370 if (ch >= 0x10000) {
3371 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
3372 ch = 0xD800 | ((ch-0x10000) >> 10);
3373 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00003374#endif
Tim Peters772747b2001-08-09 22:21:55 +00003375 STORECHAR(ch);
3376 if (ch2)
3377 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003378 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003379
3380 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003381 return v;
Tim Peters772747b2001-08-09 22:21:55 +00003382#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00003383}
3384
3385PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
3386{
3387 if (!PyUnicode_Check(unicode)) {
3388 PyErr_BadArgument();
3389 return NULL;
3390 }
3391 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00003392 PyUnicode_GET_SIZE(unicode),
3393 NULL,
3394 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003395}
3396
3397/* --- Unicode Escape Codec ----------------------------------------------- */
3398
Fredrik Lundh06d12682001-01-24 07:59:11 +00003399static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00003400
Guido van Rossumd57fd912000-03-10 22:53:23 +00003401PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003402 Py_ssize_t size,
3403 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003405 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003406 Py_ssize_t startinpos;
3407 Py_ssize_t endinpos;
3408 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003409 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003410 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003411 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003412 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003413 char* message;
3414 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003415 PyObject *errorHandler = NULL;
3416 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003417
Guido van Rossumd57fd912000-03-10 22:53:23 +00003418 /* Escaped strings will always be longer than the resulting
3419 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003420 length after conversion to the true value.
3421 (but if the error callback returns a long replacement string
3422 we'll have to allocate more space) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003423 v = _PyUnicode_New(size);
3424 if (v == NULL)
3425 goto onError;
3426 if (size == 0)
3427 return (PyObject *)v;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003428
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003429 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003430 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003431
Guido van Rossumd57fd912000-03-10 22:53:23 +00003432 while (s < end) {
3433 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00003434 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003435 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003436
3437 /* Non-escape characters are interpreted as Unicode ordinals */
3438 if (*s != '\\') {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003439 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003440 continue;
3441 }
3442
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003443 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003444 /* \ - Escapes */
3445 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003446 c = *s++;
3447 if (s > end)
3448 c = '\0'; /* Invalid after \ */
3449 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003450
Benjamin Peterson29060642009-01-31 22:14:21 +00003451 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003452 case '\n': break;
3453 case '\\': *p++ = '\\'; break;
3454 case '\'': *p++ = '\''; break;
3455 case '\"': *p++ = '\"'; break;
3456 case 'b': *p++ = '\b'; break;
3457 case 'f': *p++ = '\014'; break; /* FF */
3458 case 't': *p++ = '\t'; break;
3459 case 'n': *p++ = '\n'; break;
3460 case 'r': *p++ = '\r'; break;
3461 case 'v': *p++ = '\013'; break; /* VT */
3462 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
3463
Benjamin Peterson29060642009-01-31 22:14:21 +00003464 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003465 case '0': case '1': case '2': case '3':
3466 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003467 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003468 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003469 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00003470 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003471 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00003472 }
Guido van Rossum0e4f6572000-05-01 21:27:20 +00003473 *p++ = x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003474 break;
3475
Benjamin Peterson29060642009-01-31 22:14:21 +00003476 /* hex escapes */
3477 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003478 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003479 digits = 2;
3480 message = "truncated \\xXX escape";
3481 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003482
Benjamin Peterson29060642009-01-31 22:14:21 +00003483 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003484 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003485 digits = 4;
3486 message = "truncated \\uXXXX escape";
3487 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003488
Benjamin Peterson29060642009-01-31 22:14:21 +00003489 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00003490 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00003491 digits = 8;
3492 message = "truncated \\UXXXXXXXX escape";
3493 hexescape:
3494 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003495 outpos = p-PyUnicode_AS_UNICODE(v);
3496 if (s+digits>end) {
3497 endinpos = size;
3498 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003499 errors, &errorHandler,
3500 "unicodeescape", "end of string in escape sequence",
3501 &starts, &end, &startinpos, &endinpos, &exc, &s,
3502 &v, &outpos, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003503 goto onError;
3504 goto nextByte;
3505 }
3506 for (i = 0; i < digits; ++i) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00003507 c = (unsigned char) s[i];
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003508 if (!ISXDIGIT(c)) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003509 endinpos = (s+i+1)-starts;
3510 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003511 errors, &errorHandler,
3512 "unicodeescape", message,
3513 &starts, &end, &startinpos, &endinpos, &exc, &s,
3514 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003515 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003516 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00003517 }
3518 chr = (chr<<4) & ~0xF;
3519 if (c >= '0' && c <= '9')
3520 chr += c - '0';
3521 else if (c >= 'a' && c <= 'f')
3522 chr += 10 + c - 'a';
3523 else
3524 chr += 10 + c - 'A';
3525 }
3526 s += i;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00003527 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003528 /* _decoding_error will have already written into the
3529 target buffer. */
3530 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003531 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00003532 /* when we get here, chr is a 32-bit unicode character */
3533 if (chr <= 0xffff)
3534 /* UCS-2 character */
3535 *p++ = (Py_UNICODE) chr;
3536 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003537 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00003538 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00003539#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003540 *p++ = chr;
3541#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00003542 chr -= 0x10000L;
3543 *p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
Fredrik Lundh45714e92001-06-26 16:39:36 +00003544 *p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003545#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00003546 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003547 endinpos = s-starts;
3548 outpos = p-PyUnicode_AS_UNICODE(v);
3549 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003550 errors, &errorHandler,
3551 "unicodeescape", "illegal Unicode character",
3552 &starts, &end, &startinpos, &endinpos, &exc, &s,
3553 &v, &outpos, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00003554 goto onError;
3555 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003556 break;
3557
Benjamin Peterson29060642009-01-31 22:14:21 +00003558 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00003559 case 'N':
3560 message = "malformed \\N character escape";
3561 if (ucnhash_CAPI == NULL) {
3562 /* load the unicode data module */
Benjamin Petersonb173f782009-05-05 22:31:58 +00003563 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00003564 if (ucnhash_CAPI == NULL)
3565 goto ucnhashError;
3566 }
3567 if (*s == '{') {
3568 const char *start = s+1;
3569 /* look for the closing brace */
3570 while (*s != '}' && s < end)
3571 s++;
3572 if (s > start && s < end && *s == '}') {
3573 /* found a name. look it up in the unicode database */
3574 message = "unknown Unicode character name";
3575 s++;
Martin v. Löwis480f1bb2006-03-09 23:38:20 +00003576 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1), &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003577 goto store;
3578 }
3579 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003580 endinpos = s-starts;
3581 outpos = p-PyUnicode_AS_UNICODE(v);
3582 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003583 errors, &errorHandler,
3584 "unicodeescape", message,
3585 &starts, &end, &startinpos, &endinpos, &exc, &s,
3586 &v, &outpos, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00003587 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00003588 break;
3589
3590 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00003591 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003592 message = "\\ at end of string";
3593 s--;
3594 endinpos = s-starts;
3595 outpos = p-PyUnicode_AS_UNICODE(v);
3596 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003597 errors, &errorHandler,
3598 "unicodeescape", message,
3599 &starts, &end, &startinpos, &endinpos, &exc, &s,
3600 &v, &outpos, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00003601 goto onError;
3602 }
3603 else {
3604 *p++ = '\\';
3605 *p++ = (unsigned char)s[-1];
3606 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00003607 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003608 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003609 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003611 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003612 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003613 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00003614 Py_XDECREF(errorHandler);
3615 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003616 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00003617
Benjamin Peterson29060642009-01-31 22:14:21 +00003618 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00003619 PyErr_SetString(
3620 PyExc_UnicodeError,
3621 "\\N escapes not supported (can't load unicodedata module)"
3622 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003623 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003624 Py_XDECREF(errorHandler);
3625 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00003626 return NULL;
3627
Benjamin Peterson29060642009-01-31 22:14:21 +00003628 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003629 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003630 Py_XDECREF(errorHandler);
3631 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003632 return NULL;
3633}
3634
3635/* Return a Unicode-Escape string version of the Unicode object.
3636
3637 If quotes is true, the string is enclosed in u"" or u'' quotes as
3638 appropriate.
3639
3640*/
3641
Thomas Wouters477c8d52006-05-27 19:21:47 +00003642Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 Py_ssize_t size,
3644 Py_UNICODE ch)
Thomas Wouters477c8d52006-05-27 19:21:47 +00003645{
3646 /* like wcschr, but doesn't stop at NULL characters */
3647
3648 while (size-- > 0) {
3649 if (*s == ch)
3650 return s;
3651 s++;
3652 }
3653
3654 return NULL;
3655}
Barry Warsaw51ac5802000-03-20 16:36:48 +00003656
Walter Dörwald79e913e2007-05-12 11:08:06 +00003657static const char *hexdigits = "0123456789abcdef";
3658
3659PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003662 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003663 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003664
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003665#ifdef Py_UNICODE_WIDE
3666 const Py_ssize_t expandsize = 10;
3667#else
3668 const Py_ssize_t expandsize = 6;
3669#endif
3670
Thomas Wouters89f507f2006-12-13 04:49:30 +00003671 /* XXX(nnorwitz): rather than over-allocating, it would be
3672 better to choose a different scheme. Perhaps scan the
3673 first N-chars of the string and allocate based on that size.
3674 */
3675 /* Initial allocation is based on the longest-possible unichr
3676 escape.
3677
3678 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
3679 unichr, so in this case it's the longest unichr escape. In
3680 narrow (UTF-16) builds this is five chars per source unichr
3681 since there are two unichrs in the surrogate pair, so in narrow
3682 (UTF-16) builds it's not the longest unichr escape.
3683
3684 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
3685 so in the narrow (UTF-16) build case it's the longest unichr
3686 escape.
3687 */
3688
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003689 if (size == 0)
3690 return PyBytes_FromStringAndSize(NULL, 0);
3691
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003692 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003693 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003694
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003695 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00003696 2
3697 + expandsize*size
3698 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003699 if (repr == NULL)
3700 return NULL;
3701
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003702 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003703
Guido van Rossumd57fd912000-03-10 22:53:23 +00003704 while (size-- > 0) {
3705 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003706
Walter Dörwald79e913e2007-05-12 11:08:06 +00003707 /* Escape backslashes */
3708 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003709 *p++ = '\\';
3710 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00003711 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003712 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003713
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00003714#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003715 /* Map 21-bit characters to '\U00xxxxxx' */
3716 else if (ch >= 0x10000) {
3717 *p++ = '\\';
3718 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003719 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
3720 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
3721 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
3722 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
3723 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
3724 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
3725 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
3726 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00003727 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003728 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003729#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003730 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3731 else if (ch >= 0xD800 && ch < 0xDC00) {
3732 Py_UNICODE ch2;
3733 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00003734
Benjamin Peterson29060642009-01-31 22:14:21 +00003735 ch2 = *s++;
3736 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00003737 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003738 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3739 *p++ = '\\';
3740 *p++ = 'U';
3741 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
3742 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
3743 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
3744 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
3745 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
3746 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
3747 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
3748 *p++ = hexdigits[ucs & 0x0000000F];
3749 continue;
3750 }
3751 /* Fall through: isolated surrogates are copied as-is */
3752 s--;
3753 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003754 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00003755#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003756
Guido van Rossumd57fd912000-03-10 22:53:23 +00003757 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00003758 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003759 *p++ = '\\';
3760 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003761 *p++ = hexdigits[(ch >> 12) & 0x000F];
3762 *p++ = hexdigits[(ch >> 8) & 0x000F];
3763 *p++ = hexdigits[(ch >> 4) & 0x000F];
3764 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00003765 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003766
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003767 /* Map special whitespace to '\t', \n', '\r' */
3768 else if (ch == '\t') {
3769 *p++ = '\\';
3770 *p++ = 't';
3771 }
3772 else if (ch == '\n') {
3773 *p++ = '\\';
3774 *p++ = 'n';
3775 }
3776 else if (ch == '\r') {
3777 *p++ = '\\';
3778 *p++ = 'r';
3779 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003780
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003781 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00003782 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00003783 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00003784 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00003785 *p++ = hexdigits[(ch >> 4) & 0x000F];
3786 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00003787 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00003788
Guido van Rossumd57fd912000-03-10 22:53:23 +00003789 /* Copy everything else as-is */
3790 else
3791 *p++ = (char) ch;
3792 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003793
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003794 assert(p - PyBytes_AS_STRING(repr) > 0);
3795 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
3796 return NULL;
3797 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003798}
3799
Alexandre Vassalotti2056bed2008-12-27 19:46:35 +00003800PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003801{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003802 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003803 if (!PyUnicode_Check(unicode)) {
3804 PyErr_BadArgument();
3805 return NULL;
3806 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00003807 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
3808 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00003809 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003810}
3811
3812/* --- Raw Unicode Escape Codec ------------------------------------------- */
3813
3814PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003815 Py_ssize_t size,
3816 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003817{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003818 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003819 Py_ssize_t startinpos;
3820 Py_ssize_t endinpos;
3821 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003822 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003823 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003824 const char *end;
3825 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003826 PyObject *errorHandler = NULL;
3827 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00003828
Guido van Rossumd57fd912000-03-10 22:53:23 +00003829 /* Escaped strings will always be longer than the resulting
3830 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003831 length after conversion to the true value. (But decoding error
3832 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003833 v = _PyUnicode_New(size);
3834 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003835 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003836 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003837 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003838 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003839 end = s + size;
3840 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003841 unsigned char c;
3842 Py_UCS4 x;
3843 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003844 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003845
Benjamin Peterson29060642009-01-31 22:14:21 +00003846 /* Non-escape characters are interpreted as Unicode ordinals */
3847 if (*s != '\\') {
3848 *p++ = (unsigned char)*s++;
3849 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003850 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003851 startinpos = s-starts;
3852
3853 /* \u-escapes are only interpreted iff the number of leading
3854 backslashes if odd */
3855 bs = s;
3856 for (;s < end;) {
3857 if (*s != '\\')
3858 break;
3859 *p++ = (unsigned char)*s++;
3860 }
3861 if (((s - bs) & 1) == 0 ||
3862 s >= end ||
3863 (*s != 'u' && *s != 'U')) {
3864 continue;
3865 }
3866 p--;
3867 count = *s=='u' ? 4 : 8;
3868 s++;
3869
3870 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
3871 outpos = p-PyUnicode_AS_UNICODE(v);
3872 for (x = 0, i = 0; i < count; ++i, ++s) {
3873 c = (unsigned char)*s;
3874 if (!ISXDIGIT(c)) {
3875 endinpos = s-starts;
3876 if (unicode_decode_call_errorhandler(
3877 errors, &errorHandler,
3878 "rawunicodeescape", "truncated \\uXXXX",
3879 &starts, &end, &startinpos, &endinpos, &exc, &s,
3880 &v, &outpos, &p))
3881 goto onError;
3882 goto nextByte;
3883 }
3884 x = (x<<4) & ~0xF;
3885 if (c >= '0' && c <= '9')
3886 x += c - '0';
3887 else if (c >= 'a' && c <= 'f')
3888 x += 10 + c - 'a';
3889 else
3890 x += 10 + c - 'A';
3891 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00003892 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00003893 /* UCS-2 character */
3894 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003895 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003896 /* UCS-4 character. Either store directly, or as
3897 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00003898#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003899 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003900#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003901 x -= 0x10000L;
3902 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
3903 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00003904#endif
3905 } else {
3906 endinpos = s-starts;
3907 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003908 if (unicode_decode_call_errorhandler(
3909 errors, &errorHandler,
3910 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00003911 &starts, &end, &startinpos, &endinpos, &exc, &s,
3912 &v, &outpos, &p))
3913 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003914 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003915 nextByte:
3916 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003917 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003918 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003919 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003920 Py_XDECREF(errorHandler);
3921 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003922 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00003923
Benjamin Peterson29060642009-01-31 22:14:21 +00003924 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003925 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003926 Py_XDECREF(errorHandler);
3927 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003928 return NULL;
3929}
3930
3931PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00003932 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003933{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003934 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003935 char *p;
3936 char *q;
3937
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003938#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003939 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003940#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003941 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003942#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00003943
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003944 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00003945 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00003946
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003947 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003948 if (repr == NULL)
3949 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00003950 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003951 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003952
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003953 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003954 while (size-- > 0) {
3955 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003956#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00003957 /* Map 32-bit characters to '\Uxxxxxxxx' */
3958 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003959 *p++ = '\\';
3960 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00003961 *p++ = hexdigits[(ch >> 28) & 0xf];
3962 *p++ = hexdigits[(ch >> 24) & 0xf];
3963 *p++ = hexdigits[(ch >> 20) & 0xf];
3964 *p++ = hexdigits[(ch >> 16) & 0xf];
3965 *p++ = hexdigits[(ch >> 12) & 0xf];
3966 *p++ = hexdigits[(ch >> 8) & 0xf];
3967 *p++ = hexdigits[(ch >> 4) & 0xf];
3968 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00003969 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003970 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00003971#else
Benjamin Peterson29060642009-01-31 22:14:21 +00003972 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
3973 if (ch >= 0xD800 && ch < 0xDC00) {
3974 Py_UNICODE ch2;
3975 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00003976
Benjamin Peterson29060642009-01-31 22:14:21 +00003977 ch2 = *s++;
3978 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00003979 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003980 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
3981 *p++ = '\\';
3982 *p++ = 'U';
3983 *p++ = hexdigits[(ucs >> 28) & 0xf];
3984 *p++ = hexdigits[(ucs >> 24) & 0xf];
3985 *p++ = hexdigits[(ucs >> 20) & 0xf];
3986 *p++ = hexdigits[(ucs >> 16) & 0xf];
3987 *p++ = hexdigits[(ucs >> 12) & 0xf];
3988 *p++ = hexdigits[(ucs >> 8) & 0xf];
3989 *p++ = hexdigits[(ucs >> 4) & 0xf];
3990 *p++ = hexdigits[ucs & 0xf];
3991 continue;
3992 }
3993 /* Fall through: isolated surrogates are copied as-is */
3994 s--;
3995 size++;
3996 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00003997#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00003998 /* Map 16-bit characters to '\uxxxx' */
3999 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00004000 *p++ = '\\';
4001 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00004002 *p++ = hexdigits[(ch >> 12) & 0xf];
4003 *p++ = hexdigits[(ch >> 8) & 0xf];
4004 *p++ = hexdigits[(ch >> 4) & 0xf];
4005 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004006 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004007 /* Copy everything else as-is */
4008 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00004009 *p++ = (char) ch;
4010 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004011 size = p - q;
4012
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004013 assert(size > 0);
4014 if (_PyBytes_Resize(&repr, size) < 0)
4015 return NULL;
4016 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004017}
4018
4019PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
4020{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004021 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004022 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00004023 PyErr_BadArgument();
4024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004025 }
Walter Dörwald711005d2007-05-12 12:03:26 +00004026 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
4027 PyUnicode_GET_SIZE(unicode));
4028
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00004029 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004030}
4031
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004032/* --- Unicode Internal Codec ------------------------------------------- */
4033
4034PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 Py_ssize_t size,
4036 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004037{
4038 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004039 Py_ssize_t startinpos;
4040 Py_ssize_t endinpos;
4041 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004042 PyUnicodeObject *v;
4043 Py_UNICODE *p;
4044 const char *end;
4045 const char *reason;
4046 PyObject *errorHandler = NULL;
4047 PyObject *exc = NULL;
4048
Neal Norwitzd43069c2006-01-08 01:12:10 +00004049#ifdef Py_UNICODE_WIDE
4050 Py_UNICODE unimax = PyUnicode_GetMax();
4051#endif
4052
Thomas Wouters89f507f2006-12-13 04:49:30 +00004053 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004054 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
4055 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004056 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004057 if (PyUnicode_GetSize((PyObject *)v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004058 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004059 p = PyUnicode_AS_UNICODE(v);
4060 end = s + size;
4061
4062 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00004063 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004064 /* We have to sanity check the raw data, otherwise doom looms for
4065 some malformed UCS-4 data. */
4066 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00004067#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004068 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00004069#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004070 end-s < Py_UNICODE_SIZE
4071 )
Benjamin Peterson29060642009-01-31 22:14:21 +00004072 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004073 startinpos = s - starts;
4074 if (end-s < Py_UNICODE_SIZE) {
4075 endinpos = end-starts;
4076 reason = "truncated input";
4077 }
4078 else {
4079 endinpos = s - starts + Py_UNICODE_SIZE;
4080 reason = "illegal code point (> 0x10FFFF)";
4081 }
4082 outpos = p - PyUnicode_AS_UNICODE(v);
4083 if (unicode_decode_call_errorhandler(
4084 errors, &errorHandler,
4085 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00004086 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00004087 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004088 goto onError;
4089 }
4090 }
4091 else {
4092 p++;
4093 s += Py_UNICODE_SIZE;
4094 }
4095 }
4096
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004097 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004098 goto onError;
4099 Py_XDECREF(errorHandler);
4100 Py_XDECREF(exc);
4101 return (PyObject *)v;
4102
Benjamin Peterson29060642009-01-31 22:14:21 +00004103 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00004104 Py_XDECREF(v);
4105 Py_XDECREF(errorHandler);
4106 Py_XDECREF(exc);
4107 return NULL;
4108}
4109
Guido van Rossumd57fd912000-03-10 22:53:23 +00004110/* --- Latin-1 Codec ------------------------------------------------------ */
4111
4112PyObject *PyUnicode_DecodeLatin1(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 Py_ssize_t size,
4114 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004115{
4116 PyUnicodeObject *v;
4117 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004118 const char *e, *unrolled_end;
Tim Petersced69f82003-09-16 20:30:58 +00004119
Guido van Rossumd57fd912000-03-10 22:53:23 +00004120 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004121 if (size == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004122 Py_UNICODE r = *(unsigned char*)s;
4123 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004124 }
4125
Guido van Rossumd57fd912000-03-10 22:53:23 +00004126 v = _PyUnicode_New(size);
4127 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004128 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004129 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004130 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131 p = PyUnicode_AS_UNICODE(v);
Antoine Pitrouab868312009-01-10 15:40:25 +00004132 e = s + size;
4133 /* Unrolling the copy makes it much faster by reducing the looping
4134 overhead. This is similar to what many memcpy() implementations do. */
4135 unrolled_end = e - 4;
4136 while (s < unrolled_end) {
4137 p[0] = (unsigned char) s[0];
4138 p[1] = (unsigned char) s[1];
4139 p[2] = (unsigned char) s[2];
4140 p[3] = (unsigned char) s[3];
4141 s += 4;
4142 p += 4;
4143 }
4144 while (s < e)
4145 *p++ = (unsigned char) *s++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004146 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004147
Benjamin Peterson29060642009-01-31 22:14:21 +00004148 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149 Py_XDECREF(v);
4150 return NULL;
4151}
4152
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153/* create or adjust a UnicodeEncodeError */
4154static void make_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004155 const char *encoding,
4156 const Py_UNICODE *unicode, Py_ssize_t size,
4157 Py_ssize_t startpos, Py_ssize_t endpos,
4158 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004159{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004160 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004161 *exceptionObject = PyUnicodeEncodeError_Create(
4162 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004163 }
4164 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004165 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
4166 goto onError;
4167 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
4168 goto onError;
4169 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
4170 goto onError;
4171 return;
4172 onError:
4173 Py_DECREF(*exceptionObject);
4174 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004175 }
4176}
4177
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004178/* raises a UnicodeEncodeError */
4179static void raise_encode_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004180 const char *encoding,
4181 const Py_UNICODE *unicode, Py_ssize_t size,
4182 Py_ssize_t startpos, Py_ssize_t endpos,
4183 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004184{
4185 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004186 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004187 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004189}
4190
4191/* error handling callback helper:
4192 build arguments, call the callback and check the arguments,
4193 put the result into newpos and return the replacement string, which
4194 has to be freed by the caller */
4195static PyObject *unicode_encode_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00004196 PyObject **errorHandler,
4197 const char *encoding, const char *reason,
4198 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
4199 Py_ssize_t startpos, Py_ssize_t endpos,
4200 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004201{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004202 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203
4204 PyObject *restuple;
4205 PyObject *resunicode;
4206
4207 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004208 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004210 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004211 }
4212
4213 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00004214 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004215 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004216 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004217
4218 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00004219 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004220 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004221 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004222 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004223 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004224 Py_DECREF(restuple);
4225 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004226 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004227 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00004228 &resunicode, newpos)) {
4229 Py_DECREF(restuple);
4230 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004232 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
4233 PyErr_SetString(PyExc_TypeError, &argparse[3]);
4234 Py_DECREF(restuple);
4235 return NULL;
4236 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004238 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004239 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004240 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
4241 Py_DECREF(restuple);
4242 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004243 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244 Py_INCREF(resunicode);
4245 Py_DECREF(restuple);
4246 return resunicode;
4247}
4248
4249static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004250 Py_ssize_t size,
4251 const char *errors,
4252 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004253{
4254 /* output object */
4255 PyObject *res;
4256 /* pointers to the beginning and end+1 of input */
4257 const Py_UNICODE *startp = p;
4258 const Py_UNICODE *endp = p + size;
4259 /* pointer to the beginning of the unencodable characters */
4260 /* const Py_UNICODE *badp = NULL; */
4261 /* pointer into the output */
4262 char *str;
4263 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00004264 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004265 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
4266 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004267 PyObject *errorHandler = NULL;
4268 PyObject *exc = NULL;
4269 /* the following variable is used for caching string comparisons
4270 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
4271 int known_errorHandler = -1;
4272
4273 /* allocate enough for a simple encoding without
4274 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004275 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00004276 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004277 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004278 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004279 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004280 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004281 ressize = size;
4282
4283 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004284 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004285
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 /* can we encode this? */
4287 if (c<limit) {
4288 /* no overflow check, because we know that the space is enough */
4289 *str++ = (char)c;
4290 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004291 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004292 else {
4293 Py_ssize_t unicodepos = p-startp;
4294 Py_ssize_t requiredsize;
4295 PyObject *repunicode;
4296 Py_ssize_t repsize;
4297 Py_ssize_t newpos;
4298 Py_ssize_t respos;
4299 Py_UNICODE *uni2;
4300 /* startpos for collecting unencodable chars */
4301 const Py_UNICODE *collstart = p;
4302 const Py_UNICODE *collend = p;
4303 /* find all unecodable characters */
4304 while ((collend < endp) && ((*collend)>=limit))
4305 ++collend;
4306 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
4307 if (known_errorHandler==-1) {
4308 if ((errors==NULL) || (!strcmp(errors, "strict")))
4309 known_errorHandler = 1;
4310 else if (!strcmp(errors, "replace"))
4311 known_errorHandler = 2;
4312 else if (!strcmp(errors, "ignore"))
4313 known_errorHandler = 3;
4314 else if (!strcmp(errors, "xmlcharrefreplace"))
4315 known_errorHandler = 4;
4316 else
4317 known_errorHandler = 0;
4318 }
4319 switch (known_errorHandler) {
4320 case 1: /* strict */
4321 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
4322 goto onError;
4323 case 2: /* replace */
4324 while (collstart++<collend)
4325 *str++ = '?'; /* fall through */
4326 case 3: /* ignore */
4327 p = collend;
4328 break;
4329 case 4: /* xmlcharrefreplace */
4330 respos = str - PyBytes_AS_STRING(res);
4331 /* determine replacement size (temporarily (mis)uses p) */
4332 for (p = collstart, repsize = 0; p < collend; ++p) {
4333 if (*p<10)
4334 repsize += 2+1+1;
4335 else if (*p<100)
4336 repsize += 2+2+1;
4337 else if (*p<1000)
4338 repsize += 2+3+1;
4339 else if (*p<10000)
4340 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004341#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004342 else
4343 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00004344#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004345 else if (*p<100000)
4346 repsize += 2+5+1;
4347 else if (*p<1000000)
4348 repsize += 2+6+1;
4349 else
4350 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004351#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004352 }
4353 requiredsize = respos+repsize+(endp-collend);
4354 if (requiredsize > ressize) {
4355 if (requiredsize<2*ressize)
4356 requiredsize = 2*ressize;
4357 if (_PyBytes_Resize(&res, requiredsize))
4358 goto onError;
4359 str = PyBytes_AS_STRING(res) + respos;
4360 ressize = requiredsize;
4361 }
4362 /* generate replacement (temporarily (mis)uses p) */
4363 for (p = collstart; p < collend; ++p) {
4364 str += sprintf(str, "&#%d;", (int)*p);
4365 }
4366 p = collend;
4367 break;
4368 default:
4369 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
4370 encoding, reason, startp, size, &exc,
4371 collstart-startp, collend-startp, &newpos);
4372 if (repunicode == NULL)
4373 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004374 if (PyBytes_Check(repunicode)) {
4375 /* Directly copy bytes result to output. */
4376 repsize = PyBytes_Size(repunicode);
4377 if (repsize > 1) {
4378 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004379 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004380 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
4381 Py_DECREF(repunicode);
4382 goto onError;
4383 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00004384 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004385 ressize += repsize-1;
4386 }
4387 memcpy(str, PyBytes_AsString(repunicode), repsize);
4388 str += repsize;
4389 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004390 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00004391 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004392 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 /* need more space? (at least enough for what we
4394 have+the replacement+the rest of the string, so
4395 we won't have to check space for encodable characters) */
4396 respos = str - PyBytes_AS_STRING(res);
4397 repsize = PyUnicode_GET_SIZE(repunicode);
4398 requiredsize = respos+repsize+(endp-collend);
4399 if (requiredsize > ressize) {
4400 if (requiredsize<2*ressize)
4401 requiredsize = 2*ressize;
4402 if (_PyBytes_Resize(&res, requiredsize)) {
4403 Py_DECREF(repunicode);
4404 goto onError;
4405 }
4406 str = PyBytes_AS_STRING(res) + respos;
4407 ressize = requiredsize;
4408 }
4409 /* check if there is anything unencodable in the replacement
4410 and copy it to the output */
4411 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
4412 c = *uni2;
4413 if (c >= limit) {
4414 raise_encode_exception(&exc, encoding, startp, size,
4415 unicodepos, unicodepos+1, reason);
4416 Py_DECREF(repunicode);
4417 goto onError;
4418 }
4419 *str = (char)c;
4420 }
4421 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004422 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004423 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004424 }
4425 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004426 /* Resize if we allocated to much */
4427 size = str - PyBytes_AS_STRING(res);
4428 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00004429 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004430 if (_PyBytes_Resize(&res, size) < 0)
4431 goto onError;
4432 }
4433
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004434 Py_XDECREF(errorHandler);
4435 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004436 return res;
4437
4438 onError:
4439 Py_XDECREF(res);
4440 Py_XDECREF(errorHandler);
4441 Py_XDECREF(exc);
4442 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004443}
4444
Guido van Rossumd57fd912000-03-10 22:53:23 +00004445PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004446 Py_ssize_t size,
4447 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004449 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004450}
4451
4452PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
4453{
4454 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 PyErr_BadArgument();
4456 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004457 }
4458 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 PyUnicode_GET_SIZE(unicode),
4460 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004461}
4462
4463/* --- 7-bit ASCII Codec -------------------------------------------------- */
4464
Guido van Rossumd57fd912000-03-10 22:53:23 +00004465PyObject *PyUnicode_DecodeASCII(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004466 Py_ssize_t size,
4467 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004468{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004469 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470 PyUnicodeObject *v;
4471 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004472 Py_ssize_t startinpos;
4473 Py_ssize_t endinpos;
4474 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475 const char *e;
4476 PyObject *errorHandler = NULL;
4477 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00004478
Guido van Rossumd57fd912000-03-10 22:53:23 +00004479 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004480 if (size == 1 && *(unsigned char*)s < 128) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 Py_UNICODE r = *(unsigned char*)s;
4482 return PyUnicode_FromUnicode(&r, 1);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00004483 }
Tim Petersced69f82003-09-16 20:30:58 +00004484
Guido van Rossumd57fd912000-03-10 22:53:23 +00004485 v = _PyUnicode_New(size);
4486 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004487 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004488 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004489 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004490 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004491 e = s + size;
4492 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004493 register unsigned char c = (unsigned char)*s;
4494 if (c < 128) {
4495 *p++ = c;
4496 ++s;
4497 }
4498 else {
4499 startinpos = s-starts;
4500 endinpos = startinpos + 1;
4501 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
4502 if (unicode_decode_call_errorhandler(
4503 errors, &errorHandler,
4504 "ascii", "ordinal not in range(128)",
4505 &starts, &e, &startinpos, &endinpos, &exc, &s,
4506 &v, &outpos, &p))
4507 goto onError;
4508 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004509 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00004510 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4512 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004513 Py_XDECREF(errorHandler);
4514 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004515 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004516
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004519 Py_XDECREF(errorHandler);
4520 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521 return NULL;
4522}
4523
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004525 Py_ssize_t size,
4526 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004528 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529}
4530
4531PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
4532{
4533 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004534 PyErr_BadArgument();
4535 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004536 }
4537 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004538 PyUnicode_GET_SIZE(unicode),
4539 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004540}
4541
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004542#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004543
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004544/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004545
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00004546#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004547#define NEED_RETRY
4548#endif
4549
4550/* XXX This code is limited to "true" double-byte encodings, as
4551 a) it assumes an incomplete character consists of a single byte, and
4552 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00004553 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004554
4555static int is_dbcs_lead_byte(const char *s, int offset)
4556{
4557 const char *curr = s + offset;
4558
4559 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 const char *prev = CharPrev(s, curr);
4561 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004562 }
4563 return 0;
4564}
4565
4566/*
4567 * Decode MBCS string into unicode object. If 'final' is set, converts
4568 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
4569 */
4570static int decode_mbcs(PyUnicodeObject **v,
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 const char *s, /* MBCS string */
4572 int size, /* sizeof MBCS string */
Victor Stinner554f3f02010-06-16 23:33:54 +00004573 int final,
4574 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004575{
4576 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00004577 Py_ssize_t n;
4578 DWORD usize;
4579 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004580
4581 assert(size >= 0);
4582
Victor Stinner554f3f02010-06-16 23:33:54 +00004583 /* check and handle 'errors' arg */
4584 if (errors==NULL || strcmp(errors, "strict")==0)
4585 flags = MB_ERR_INVALID_CHARS;
4586 else if (strcmp(errors, "ignore")==0)
4587 flags = 0;
4588 else {
4589 PyErr_Format(PyExc_ValueError,
4590 "mbcs encoding does not support errors='%s'",
4591 errors);
4592 return -1;
4593 }
4594
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004595 /* Skip trailing lead-byte unless 'final' is set */
4596 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00004597 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004598
4599 /* First get the size of the result */
4600 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004601 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
4602 if (usize==0)
4603 goto mbcs_decode_error;
4604 } else
4605 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004606
4607 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004608 /* Create unicode object */
4609 *v = _PyUnicode_New(usize);
4610 if (*v == NULL)
4611 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004612 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004613 }
4614 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004615 /* Extend unicode object */
4616 n = PyUnicode_GET_SIZE(*v);
4617 if (_PyUnicode_Resize(v, n + usize) < 0)
4618 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004619 }
4620
4621 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00004622 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004623 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004624 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
4625 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00004626 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004627 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004628 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00004629
4630mbcs_decode_error:
4631 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
4632 we raise a UnicodeDecodeError - else it is a 'generic'
4633 windows error
4634 */
4635 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
4636 /* Ideally, we should get reason from FormatMessage - this
4637 is the Windows 2000 English version of the message
4638 */
4639 PyObject *exc = NULL;
4640 const char *reason = "No mapping for the Unicode character exists "
4641 "in the target multi-byte code page.";
4642 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
4643 if (exc != NULL) {
4644 PyCodec_StrictErrors(exc);
4645 Py_DECREF(exc);
4646 }
4647 } else {
4648 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4649 }
4650 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004651}
4652
4653PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004654 Py_ssize_t size,
4655 const char *errors,
4656 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004657{
4658 PyUnicodeObject *v = NULL;
4659 int done;
4660
4661 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004662 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004663
4664#ifdef NEED_RETRY
4665 retry:
4666 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004667 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004668 else
4669#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004670 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004671
4672 if (done < 0) {
4673 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00004674 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004675 }
4676
4677 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004678 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004679
4680#ifdef NEED_RETRY
4681 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 s += done;
4683 size -= done;
4684 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004685 }
4686#endif
4687
4688 return (PyObject *)v;
4689}
4690
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004691PyObject *PyUnicode_DecodeMBCS(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004692 Py_ssize_t size,
4693 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004694{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004695 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
4696}
4697
4698/*
4699 * Convert unicode into string object (MBCS).
4700 * Returns 0 if succeed, -1 otherwise.
4701 */
4702static int encode_mbcs(PyObject **repr,
Benjamin Peterson29060642009-01-31 22:14:21 +00004703 const Py_UNICODE *p, /* unicode */
Victor Stinner554f3f02010-06-16 23:33:54 +00004704 int size, /* size of unicode */
4705 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004706{
Victor Stinner554f3f02010-06-16 23:33:54 +00004707 BOOL usedDefaultChar = FALSE;
4708 BOOL *pusedDefaultChar;
4709 int mbcssize;
4710 Py_ssize_t n;
4711 PyObject *exc = NULL;
4712 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004713
4714 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004715
Victor Stinner554f3f02010-06-16 23:33:54 +00004716 /* check and handle 'errors' arg */
4717 if (errors==NULL || strcmp(errors, "strict")==0) {
4718 flags = WC_NO_BEST_FIT_CHARS;
4719 pusedDefaultChar = &usedDefaultChar;
4720 } else if (strcmp(errors, "replace")==0) {
4721 flags = 0;
4722 pusedDefaultChar = NULL;
4723 } else {
4724 PyErr_Format(PyExc_ValueError,
4725 "mbcs encoding does not support errors='%s'",
4726 errors);
4727 return -1;
4728 }
4729
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004730 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004731 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00004732 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
4733 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00004734 if (mbcssize == 0) {
4735 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4736 return -1;
4737 }
Victor Stinner554f3f02010-06-16 23:33:54 +00004738 /* If we used a default char, then we failed! */
4739 if (pusedDefaultChar && *pusedDefaultChar)
4740 goto mbcs_encode_error;
4741 } else {
4742 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004743 }
4744
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004745 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004746 /* Create string object */
4747 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
4748 if (*repr == NULL)
4749 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00004750 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004751 }
4752 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004753 /* Extend string object */
4754 n = PyBytes_Size(*repr);
4755 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
4756 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004757 }
4758
4759 /* Do the conversion */
4760 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004761 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00004762 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
4763 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004764 PyErr_SetFromWindowsErrWithFilename(0, NULL);
4765 return -1;
4766 }
Victor Stinner554f3f02010-06-16 23:33:54 +00004767 if (pusedDefaultChar && *pusedDefaultChar)
4768 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004769 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004770 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00004771
4772mbcs_encode_error:
4773 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
4774 Py_XDECREF(exc);
4775 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004776}
4777
4778PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00004779 Py_ssize_t size,
4780 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004781{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004782 PyObject *repr = NULL;
4783 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00004784
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004785#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00004786 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004787 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00004788 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004789 else
4790#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00004791 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004792
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004793 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004794 Py_XDECREF(repr);
4795 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004796 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004797
4798#ifdef NEED_RETRY
4799 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004800 p += INT_MAX;
4801 size -= INT_MAX;
4802 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004803 }
4804#endif
4805
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004806 return repr;
4807}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00004808
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004809PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
4810{
4811 if (!PyUnicode_Check(unicode)) {
4812 PyErr_BadArgument();
4813 return NULL;
4814 }
4815 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004816 PyUnicode_GET_SIZE(unicode),
4817 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00004818}
4819
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004820#undef NEED_RETRY
4821
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004822#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00004823
Guido van Rossumd57fd912000-03-10 22:53:23 +00004824/* --- Character Mapping Codec -------------------------------------------- */
4825
Guido van Rossumd57fd912000-03-10 22:53:23 +00004826PyObject *PyUnicode_DecodeCharmap(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004827 Py_ssize_t size,
4828 PyObject *mapping,
4829 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004830{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004831 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004832 Py_ssize_t startinpos;
4833 Py_ssize_t endinpos;
4834 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004835 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836 PyUnicodeObject *v;
4837 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004838 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004839 PyObject *errorHandler = NULL;
4840 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004841 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004842 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00004843
Guido van Rossumd57fd912000-03-10 22:53:23 +00004844 /* Default to Latin-1 */
4845 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004847
4848 v = _PyUnicode_New(size);
4849 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004850 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004851 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004852 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004853 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004854 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004855 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004856 mapstring = PyUnicode_AS_UNICODE(mapping);
4857 maplen = PyUnicode_GET_SIZE(mapping);
4858 while (s < e) {
4859 unsigned char ch = *s;
4860 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004861
Benjamin Peterson29060642009-01-31 22:14:21 +00004862 if (ch < maplen)
4863 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 if (x == 0xfffe) {
4866 /* undefined mapping */
4867 outpos = p-PyUnicode_AS_UNICODE(v);
4868 startinpos = s-starts;
4869 endinpos = startinpos+1;
4870 if (unicode_decode_call_errorhandler(
4871 errors, &errorHandler,
4872 "charmap", "character maps to <undefined>",
4873 &starts, &e, &startinpos, &endinpos, &exc, &s,
4874 &v, &outpos, &p)) {
4875 goto onError;
4876 }
4877 continue;
4878 }
4879 *p++ = x;
4880 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004881 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004882 }
4883 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00004884 while (s < e) {
4885 unsigned char ch = *s;
4886 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00004887
Benjamin Peterson29060642009-01-31 22:14:21 +00004888 /* Get mapping (char ordinal -> integer, Unicode char or None) */
4889 w = PyLong_FromLong((long)ch);
4890 if (w == NULL)
4891 goto onError;
4892 x = PyObject_GetItem(mapping, w);
4893 Py_DECREF(w);
4894 if (x == NULL) {
4895 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
4896 /* No mapping found means: mapping is undefined. */
4897 PyErr_Clear();
4898 x = Py_None;
4899 Py_INCREF(x);
4900 } else
4901 goto onError;
4902 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004903
Benjamin Peterson29060642009-01-31 22:14:21 +00004904 /* Apply mapping */
4905 if (PyLong_Check(x)) {
4906 long value = PyLong_AS_LONG(x);
4907 if (value < 0 || value > 65535) {
4908 PyErr_SetString(PyExc_TypeError,
4909 "character mapping must be in range(65536)");
4910 Py_DECREF(x);
4911 goto onError;
4912 }
4913 *p++ = (Py_UNICODE)value;
4914 }
4915 else if (x == Py_None) {
4916 /* undefined mapping */
4917 outpos = p-PyUnicode_AS_UNICODE(v);
4918 startinpos = s-starts;
4919 endinpos = startinpos+1;
4920 if (unicode_decode_call_errorhandler(
4921 errors, &errorHandler,
4922 "charmap", "character maps to <undefined>",
4923 &starts, &e, &startinpos, &endinpos, &exc, &s,
4924 &v, &outpos, &p)) {
4925 Py_DECREF(x);
4926 goto onError;
4927 }
4928 Py_DECREF(x);
4929 continue;
4930 }
4931 else if (PyUnicode_Check(x)) {
4932 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004933
Benjamin Peterson29060642009-01-31 22:14:21 +00004934 if (targetsize == 1)
4935 /* 1-1 mapping */
4936 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00004937
Benjamin Peterson29060642009-01-31 22:14:21 +00004938 else if (targetsize > 1) {
4939 /* 1-n mapping */
4940 if (targetsize > extrachars) {
4941 /* resize first */
4942 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
4943 Py_ssize_t needed = (targetsize - extrachars) + \
4944 (targetsize << 2);
4945 extrachars += needed;
4946 /* XXX overflow detection missing */
4947 if (_PyUnicode_Resize(&v,
4948 PyUnicode_GET_SIZE(v) + needed) < 0) {
4949 Py_DECREF(x);
4950 goto onError;
4951 }
4952 p = PyUnicode_AS_UNICODE(v) + oldpos;
4953 }
4954 Py_UNICODE_COPY(p,
4955 PyUnicode_AS_UNICODE(x),
4956 targetsize);
4957 p += targetsize;
4958 extrachars -= targetsize;
4959 }
4960 /* 1-0 mapping: skip the character */
4961 }
4962 else {
4963 /* wrong return value */
4964 PyErr_SetString(PyExc_TypeError,
4965 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00004966 Py_DECREF(x);
4967 goto onError;
4968 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 Py_DECREF(x);
4970 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004971 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004972 }
4973 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00004974 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
4975 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004976 Py_XDECREF(errorHandler);
4977 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004978 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00004979
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004981 Py_XDECREF(errorHandler);
4982 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004983 Py_XDECREF(v);
4984 return NULL;
4985}
4986
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004987/* Charmap encoding: the lookup table */
4988
4989struct encoding_map{
Benjamin Peterson29060642009-01-31 22:14:21 +00004990 PyObject_HEAD
4991 unsigned char level1[32];
4992 int count2, count3;
4993 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004994};
4995
4996static PyObject*
4997encoding_map_size(PyObject *obj, PyObject* args)
4998{
4999 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005000 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005002}
5003
5004static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005005 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00005006 PyDoc_STR("Return the size (in bytes) of this object") },
5007 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005008};
5009
5010static void
5011encoding_map_dealloc(PyObject* o)
5012{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005013 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005014}
5015
5016static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005017 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005018 "EncodingMap", /*tp_name*/
5019 sizeof(struct encoding_map), /*tp_basicsize*/
5020 0, /*tp_itemsize*/
5021 /* methods */
5022 encoding_map_dealloc, /*tp_dealloc*/
5023 0, /*tp_print*/
5024 0, /*tp_getattr*/
5025 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00005026 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 0, /*tp_repr*/
5028 0, /*tp_as_number*/
5029 0, /*tp_as_sequence*/
5030 0, /*tp_as_mapping*/
5031 0, /*tp_hash*/
5032 0, /*tp_call*/
5033 0, /*tp_str*/
5034 0, /*tp_getattro*/
5035 0, /*tp_setattro*/
5036 0, /*tp_as_buffer*/
5037 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5038 0, /*tp_doc*/
5039 0, /*tp_traverse*/
5040 0, /*tp_clear*/
5041 0, /*tp_richcompare*/
5042 0, /*tp_weaklistoffset*/
5043 0, /*tp_iter*/
5044 0, /*tp_iternext*/
5045 encoding_map_methods, /*tp_methods*/
5046 0, /*tp_members*/
5047 0, /*tp_getset*/
5048 0, /*tp_base*/
5049 0, /*tp_dict*/
5050 0, /*tp_descr_get*/
5051 0, /*tp_descr_set*/
5052 0, /*tp_dictoffset*/
5053 0, /*tp_init*/
5054 0, /*tp_alloc*/
5055 0, /*tp_new*/
5056 0, /*tp_free*/
5057 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005058};
5059
5060PyObject*
5061PyUnicode_BuildEncodingMap(PyObject* string)
5062{
5063 Py_UNICODE *decode;
5064 PyObject *result;
5065 struct encoding_map *mresult;
5066 int i;
5067 int need_dict = 0;
5068 unsigned char level1[32];
5069 unsigned char level2[512];
5070 unsigned char *mlevel1, *mlevel2, *mlevel3;
5071 int count2 = 0, count3 = 0;
5072
5073 if (!PyUnicode_Check(string) || PyUnicode_GetSize(string) != 256) {
5074 PyErr_BadArgument();
5075 return NULL;
5076 }
5077 decode = PyUnicode_AS_UNICODE(string);
5078 memset(level1, 0xFF, sizeof level1);
5079 memset(level2, 0xFF, sizeof level2);
5080
5081 /* If there isn't a one-to-one mapping of NULL to \0,
5082 or if there are non-BMP characters, we need to use
5083 a mapping dictionary. */
5084 if (decode[0] != 0)
5085 need_dict = 1;
5086 for (i = 1; i < 256; i++) {
5087 int l1, l2;
5088 if (decode[i] == 0
Benjamin Peterson29060642009-01-31 22:14:21 +00005089#ifdef Py_UNICODE_WIDE
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005090 || decode[i] > 0xFFFF
Benjamin Peterson29060642009-01-31 22:14:21 +00005091#endif
5092 ) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005093 need_dict = 1;
5094 break;
5095 }
5096 if (decode[i] == 0xFFFE)
5097 /* unmapped character */
5098 continue;
5099 l1 = decode[i] >> 11;
5100 l2 = decode[i] >> 7;
5101 if (level1[l1] == 0xFF)
5102 level1[l1] = count2++;
5103 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00005104 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005105 }
5106
5107 if (count2 >= 0xFF || count3 >= 0xFF)
5108 need_dict = 1;
5109
5110 if (need_dict) {
5111 PyObject *result = PyDict_New();
5112 PyObject *key, *value;
5113 if (!result)
5114 return NULL;
5115 for (i = 0; i < 256; i++) {
5116 key = value = NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00005117 key = PyLong_FromLong(decode[i]);
5118 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005119 if (!key || !value)
5120 goto failed1;
5121 if (PyDict_SetItem(result, key, value) == -1)
5122 goto failed1;
5123 Py_DECREF(key);
5124 Py_DECREF(value);
5125 }
5126 return result;
5127 failed1:
5128 Py_XDECREF(key);
5129 Py_XDECREF(value);
5130 Py_DECREF(result);
5131 return NULL;
5132 }
5133
5134 /* Create a three-level trie */
5135 result = PyObject_MALLOC(sizeof(struct encoding_map) +
5136 16*count2 + 128*count3 - 1);
5137 if (!result)
5138 return PyErr_NoMemory();
5139 PyObject_Init(result, &EncodingMapType);
5140 mresult = (struct encoding_map*)result;
5141 mresult->count2 = count2;
5142 mresult->count3 = count3;
5143 mlevel1 = mresult->level1;
5144 mlevel2 = mresult->level23;
5145 mlevel3 = mresult->level23 + 16*count2;
5146 memcpy(mlevel1, level1, 32);
5147 memset(mlevel2, 0xFF, 16*count2);
5148 memset(mlevel3, 0, 128*count3);
5149 count3 = 0;
5150 for (i = 1; i < 256; i++) {
5151 int o1, o2, o3, i2, i3;
5152 if (decode[i] == 0xFFFE)
5153 /* unmapped character */
5154 continue;
5155 o1 = decode[i]>>11;
5156 o2 = (decode[i]>>7) & 0xF;
5157 i2 = 16*mlevel1[o1] + o2;
5158 if (mlevel2[i2] == 0xFF)
5159 mlevel2[i2] = count3++;
5160 o3 = decode[i] & 0x7F;
5161 i3 = 128*mlevel2[i2] + o3;
5162 mlevel3[i3] = i;
5163 }
5164 return result;
5165}
5166
5167static int
5168encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
5169{
5170 struct encoding_map *map = (struct encoding_map*)mapping;
5171 int l1 = c>>11;
5172 int l2 = (c>>7) & 0xF;
5173 int l3 = c & 0x7F;
5174 int i;
5175
5176#ifdef Py_UNICODE_WIDE
5177 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005179 }
5180#endif
5181 if (c == 0)
5182 return 0;
5183 /* level 1*/
5184 i = map->level1[l1];
5185 if (i == 0xFF) {
5186 return -1;
5187 }
5188 /* level 2*/
5189 i = map->level23[16*i+l2];
5190 if (i == 0xFF) {
5191 return -1;
5192 }
5193 /* level 3 */
5194 i = map->level23[16*map->count2 + 128*i + l3];
5195 if (i == 0) {
5196 return -1;
5197 }
5198 return i;
5199}
5200
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005201/* Lookup the character ch in the mapping. If the character
5202 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00005203 error occurred). */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005204static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005205{
Christian Heimes217cfd12007-12-02 14:31:20 +00005206 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005207 PyObject *x;
5208
5209 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005210 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005211 x = PyObject_GetItem(mapping, w);
5212 Py_DECREF(w);
5213 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005214 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5215 /* No mapping found means: mapping is undefined. */
5216 PyErr_Clear();
5217 x = Py_None;
5218 Py_INCREF(x);
5219 return x;
5220 } else
5221 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00005223 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00005225 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005226 long value = PyLong_AS_LONG(x);
5227 if (value < 0 || value > 255) {
5228 PyErr_SetString(PyExc_TypeError,
5229 "character mapping must be in range(256)");
5230 Py_DECREF(x);
5231 return NULL;
5232 }
5233 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005234 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005235 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005237 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005238 /* wrong return value */
5239 PyErr_Format(PyExc_TypeError,
5240 "character mapping must return integer, bytes or None, not %.400s",
5241 x->ob_type->tp_name);
5242 Py_DECREF(x);
5243 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005244 }
5245}
5246
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005247static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00005248charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005249{
Benjamin Peterson14339b62009-01-31 16:36:08 +00005250 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
5251 /* exponentially overallocate to minimize reallocations */
5252 if (requiredsize < 2*outsize)
5253 requiredsize = 2*outsize;
5254 if (_PyBytes_Resize(outobj, requiredsize))
5255 return -1;
5256 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005257}
5258
Benjamin Peterson14339b62009-01-31 16:36:08 +00005259typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00005260 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005261}charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005262/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00005263 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005264 space is available. Return a new reference to the object that
5265 was put in the output buffer, or Py_None, if the mapping was undefined
5266 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00005267 reallocation error occurred. The caller must decref the result */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005268static
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005269charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00005270 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005271{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005272 PyObject *rep;
5273 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00005274 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005275
Christian Heimes90aa7642007-12-19 02:45:37 +00005276 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005277 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00005278 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005279 if (res == -1)
5280 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00005281 if (outsize<requiredsize)
5282 if (charmapencode_resize(outobj, outpos, requiredsize))
5283 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00005284 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005285 outstart[(*outpos)++] = (char)res;
5286 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005287 }
5288
5289 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005290 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005291 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005292 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 Py_DECREF(rep);
5294 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005295 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 if (PyLong_Check(rep)) {
5297 Py_ssize_t requiredsize = *outpos+1;
5298 if (outsize<requiredsize)
5299 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5300 Py_DECREF(rep);
5301 return enc_EXCEPTION;
5302 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005303 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005305 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 else {
5307 const char *repchars = PyBytes_AS_STRING(rep);
5308 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
5309 Py_ssize_t requiredsize = *outpos+repsize;
5310 if (outsize<requiredsize)
5311 if (charmapencode_resize(outobj, outpos, requiredsize)) {
5312 Py_DECREF(rep);
5313 return enc_EXCEPTION;
5314 }
Christian Heimes72b710a2008-05-26 13:28:38 +00005315 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00005316 memcpy(outstart + *outpos, repchars, repsize);
5317 *outpos += repsize;
5318 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005319 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005320 Py_DECREF(rep);
5321 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005322}
5323
5324/* handle an error in PyUnicode_EncodeCharmap
5325 Return 0 on success, -1 on error */
5326static
5327int charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00005328 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005329 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00005330 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00005331 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005332{
5333 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005334 Py_ssize_t repsize;
5335 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005336 Py_UNICODE *uni2;
5337 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005338 Py_ssize_t collstartpos = *inpos;
5339 Py_ssize_t collendpos = *inpos+1;
5340 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005341 char *encoding = "charmap";
5342 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005343 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005344
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005345 /* find all unencodable characters */
5346 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005347 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00005348 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005349 int res = encoding_map_lookup(p[collendpos], mapping);
5350 if (res != -1)
5351 break;
5352 ++collendpos;
5353 continue;
5354 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005355
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 rep = charmapencode_lookup(p[collendpos], mapping);
5357 if (rep==NULL)
5358 return -1;
5359 else if (rep!=Py_None) {
5360 Py_DECREF(rep);
5361 break;
5362 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005363 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005365 }
5366 /* cache callback name lookup
5367 * (if not done yet, i.e. it's the first error) */
5368 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005369 if ((errors==NULL) || (!strcmp(errors, "strict")))
5370 *known_errorHandler = 1;
5371 else if (!strcmp(errors, "replace"))
5372 *known_errorHandler = 2;
5373 else if (!strcmp(errors, "ignore"))
5374 *known_errorHandler = 3;
5375 else if (!strcmp(errors, "xmlcharrefreplace"))
5376 *known_errorHandler = 4;
5377 else
5378 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379 }
5380 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005381 case 1: /* strict */
5382 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5383 return -1;
5384 case 2: /* replace */
5385 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005386 x = charmapencode_output('?', mapping, res, respos);
5387 if (x==enc_EXCEPTION) {
5388 return -1;
5389 }
5390 else if (x==enc_FAILED) {
5391 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5392 return -1;
5393 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005394 }
5395 /* fall through */
5396 case 3: /* ignore */
5397 *inpos = collendpos;
5398 break;
5399 case 4: /* xmlcharrefreplace */
5400 /* generate replacement (temporarily (mis)uses p) */
5401 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005402 char buffer[2+29+1+1];
5403 char *cp;
5404 sprintf(buffer, "&#%d;", (int)p[collpos]);
5405 for (cp = buffer; *cp; ++cp) {
5406 x = charmapencode_output(*cp, mapping, res, respos);
5407 if (x==enc_EXCEPTION)
5408 return -1;
5409 else if (x==enc_FAILED) {
5410 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5411 return -1;
5412 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005413 }
5414 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005415 *inpos = collendpos;
5416 break;
5417 default:
5418 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00005419 encoding, reason, p, size, exceptionObject,
5420 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005421 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005423 if (PyBytes_Check(repunicode)) {
5424 /* Directly copy bytes result to output. */
5425 Py_ssize_t outsize = PyBytes_Size(*res);
5426 Py_ssize_t requiredsize;
5427 repsize = PyBytes_Size(repunicode);
5428 requiredsize = *respos + repsize;
5429 if (requiredsize > outsize)
5430 /* Make room for all additional bytes. */
5431 if (charmapencode_resize(res, respos, requiredsize)) {
5432 Py_DECREF(repunicode);
5433 return -1;
5434 }
5435 memcpy(PyBytes_AsString(*res) + *respos,
5436 PyBytes_AsString(repunicode), repsize);
5437 *respos += repsize;
5438 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005439 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005440 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005441 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005442 /* generate replacement */
5443 repsize = PyUnicode_GET_SIZE(repunicode);
5444 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005445 x = charmapencode_output(*uni2, mapping, res, respos);
5446 if (x==enc_EXCEPTION) {
5447 return -1;
5448 }
5449 else if (x==enc_FAILED) {
5450 Py_DECREF(repunicode);
5451 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
5452 return -1;
5453 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005454 }
5455 *inpos = newpos;
5456 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005457 }
5458 return 0;
5459}
5460
Guido van Rossumd57fd912000-03-10 22:53:23 +00005461PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005462 Py_ssize_t size,
5463 PyObject *mapping,
5464 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005466 /* output object */
5467 PyObject *res = NULL;
5468 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005469 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005470 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005471 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005472 PyObject *errorHandler = NULL;
5473 PyObject *exc = NULL;
5474 /* the following variable is used for caching string comparisons
5475 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5476 * 3=ignore, 4=xmlcharrefreplace */
5477 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478
5479 /* Default to Latin-1 */
5480 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005481 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005482
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005483 /* allocate enough for a simple encoding without
5484 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00005485 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005486 if (res == NULL)
5487 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005488 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005490
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005491 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005492 /* try to encode it */
5493 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
5494 if (x==enc_EXCEPTION) /* error */
5495 goto onError;
5496 if (x==enc_FAILED) { /* unencodable character */
5497 if (charmap_encoding_error(p, size, &inpos, mapping,
5498 &exc,
5499 &known_errorHandler, &errorHandler, errors,
5500 &res, &respos)) {
5501 goto onError;
5502 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005503 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 else
5505 /* done with this character => adjust input position */
5506 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005507 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005508
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005509 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00005510 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005511 if (_PyBytes_Resize(&res, respos) < 0)
5512 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005513
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005514 Py_XDECREF(exc);
5515 Py_XDECREF(errorHandler);
5516 return res;
5517
Benjamin Peterson29060642009-01-31 22:14:21 +00005518 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005519 Py_XDECREF(res);
5520 Py_XDECREF(exc);
5521 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005522 return NULL;
5523}
5524
5525PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
Benjamin Peterson29060642009-01-31 22:14:21 +00005526 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527{
5528 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005529 PyErr_BadArgument();
5530 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531 }
5532 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005533 PyUnicode_GET_SIZE(unicode),
5534 mapping,
5535 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536}
5537
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538/* create or adjust a UnicodeTranslateError */
5539static void make_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 const Py_UNICODE *unicode, Py_ssize_t size,
5541 Py_ssize_t startpos, Py_ssize_t endpos,
5542 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005544 if (*exceptionObject == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005545 *exceptionObject = PyUnicodeTranslateError_Create(
Benjamin Peterson29060642009-01-31 22:14:21 +00005546 unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005547 }
5548 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005549 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
5550 goto onError;
5551 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
5552 goto onError;
5553 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
5554 goto onError;
5555 return;
5556 onError:
5557 Py_DECREF(*exceptionObject);
5558 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559 }
5560}
5561
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005562/* raises a UnicodeTranslateError */
5563static void raise_translate_exception(PyObject **exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005564 const Py_UNICODE *unicode, Py_ssize_t size,
5565 Py_ssize_t startpos, Py_ssize_t endpos,
5566 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005567{
5568 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005569 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005570 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005572}
5573
5574/* error handling callback helper:
5575 build arguments, call the callback and check the arguments,
5576 put the result into newpos and return the replacement string, which
5577 has to be freed by the caller */
5578static PyObject *unicode_translate_call_errorhandler(const char *errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 PyObject **errorHandler,
5580 const char *reason,
5581 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5582 Py_ssize_t startpos, Py_ssize_t endpos,
5583 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005584{
Benjamin Peterson142957c2008-07-04 19:55:29 +00005585 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005586
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005587 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005588 PyObject *restuple;
5589 PyObject *resunicode;
5590
5591 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005592 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005593 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005594 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005595 }
5596
5597 make_translate_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005599 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005601
5602 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005603 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005604 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005605 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005606 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00005607 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005608 Py_DECREF(restuple);
5609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005610 }
5611 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00005612 &resunicode, &i_newpos)) {
5613 Py_DECREF(restuple);
5614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00005616 if (i_newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005617 *newpos = size+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005618 else
5619 *newpos = i_newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005620 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005621 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5622 Py_DECREF(restuple);
5623 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005624 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 Py_INCREF(resunicode);
5626 Py_DECREF(restuple);
5627 return resunicode;
5628}
5629
5630/* Lookup the character ch in the mapping and put the result in result,
5631 which must be decrefed by the caller.
5632 Return 0 on success, -1 on error */
5633static
5634int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
5635{
Christian Heimes217cfd12007-12-02 14:31:20 +00005636 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005637 PyObject *x;
5638
5639 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005640 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005641 x = PyObject_GetItem(mapping, w);
5642 Py_DECREF(w);
5643 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005644 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
5645 /* No mapping found means: use 1:1 mapping. */
5646 PyErr_Clear();
5647 *result = NULL;
5648 return 0;
5649 } else
5650 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005651 }
5652 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005653 *result = x;
5654 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005655 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005656 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005657 long value = PyLong_AS_LONG(x);
5658 long max = PyUnicode_GetMax();
5659 if (value < 0 || value > max) {
5660 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00005661 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 Py_DECREF(x);
5663 return -1;
5664 }
5665 *result = x;
5666 return 0;
5667 }
5668 else if (PyUnicode_Check(x)) {
5669 *result = x;
5670 return 0;
5671 }
5672 else {
5673 /* wrong return value */
5674 PyErr_SetString(PyExc_TypeError,
5675 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00005676 Py_DECREF(x);
5677 return -1;
5678 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005679}
5680/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00005681 if not reallocate and adjust various state variables.
5682 Return 0 on success, -1 on error */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005683static
Walter Dörwald4894c302003-10-24 14:25:28 +00005684int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005685 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005686{
Martin v. Löwis18e16552006-02-15 17:27:45 +00005687 Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
Walter Dörwald4894c302003-10-24 14:25:28 +00005688 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 /* remember old output position */
5690 Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
5691 /* exponentially overallocate to minimize reallocations */
5692 if (requiredsize < 2 * oldsize)
5693 requiredsize = 2 * oldsize;
5694 if (PyUnicode_Resize(outobj, requiredsize) < 0)
5695 return -1;
5696 *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005697 }
5698 return 0;
5699}
5700/* lookup the character, put the result in the output string and adjust
5701 various state variables. Return a new reference to the object that
5702 was put in the output buffer in *result, or Py_None, if the mapping was
5703 undefined (in which case no character was written).
5704 The called must decref result.
5705 Return 0 on success, -1 on error. */
5706static
Walter Dörwald4894c302003-10-24 14:25:28 +00005707int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
5709 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710{
Walter Dörwald4894c302003-10-24 14:25:28 +00005711 if (charmaptranslate_lookup(*curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00005712 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005713 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 /* not found => default to 1:1 mapping */
5715 *(*outp)++ = *curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005716 }
5717 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00005719 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 /* no overflow check, because we know that the space is enough */
5721 *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005722 }
5723 else if (PyUnicode_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
5725 if (repsize==1) {
5726 /* no overflow check, because we know that the space is enough */
5727 *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
5728 }
5729 else if (repsize!=0) {
5730 /* more than one character */
5731 Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
5732 (insize - (curinp-startinp)) +
5733 repsize - 1;
5734 if (charmaptranslate_makespace(outobj, outp, requiredsize))
5735 return -1;
5736 memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
5737 *outp += repsize;
5738 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 }
5740 else
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742 return 0;
5743}
5744
5745PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Benjamin Peterson29060642009-01-31 22:14:21 +00005746 Py_ssize_t size,
5747 PyObject *mapping,
5748 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 /* output object */
5751 PyObject *res = NULL;
5752 /* pointers to the beginning and end+1 of input */
5753 const Py_UNICODE *startp = p;
5754 const Py_UNICODE *endp = p + size;
5755 /* pointer into the output */
5756 Py_UNICODE *str;
5757 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005758 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 char *reason = "character maps to <undefined>";
5760 PyObject *errorHandler = NULL;
5761 PyObject *exc = NULL;
5762 /* the following variable is used for caching string comparisons
5763 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
5764 * 3=ignore, 4=xmlcharrefreplace */
5765 int known_errorHandler = -1;
5766
Guido van Rossumd57fd912000-03-10 22:53:23 +00005767 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 PyErr_BadArgument();
5769 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005770 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771
5772 /* allocate enough for a simple 1:1 translation without
5773 replacements, if we need more, we'll resize */
5774 res = PyUnicode_FromUnicode(NULL, size);
5775 if (res == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 return res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 str = PyUnicode_AS_UNICODE(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005781 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 /* try to encode it */
5783 PyObject *x = NULL;
5784 if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
5785 Py_XDECREF(x);
5786 goto onError;
5787 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005788 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 if (x!=Py_None) /* it worked => adjust input pointer */
5790 ++p;
5791 else { /* untranslatable character */
5792 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
5793 Py_ssize_t repsize;
5794 Py_ssize_t newpos;
5795 Py_UNICODE *uni2;
5796 /* startpos for collecting untranslatable chars */
5797 const Py_UNICODE *collstart = p;
5798 const Py_UNICODE *collend = p+1;
5799 const Py_UNICODE *coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005800
Benjamin Peterson29060642009-01-31 22:14:21 +00005801 /* find all untranslatable characters */
5802 while (collend < endp) {
5803 if (charmaptranslate_lookup(*collend, mapping, &x))
5804 goto onError;
5805 Py_XDECREF(x);
5806 if (x!=Py_None)
5807 break;
5808 ++collend;
5809 }
5810 /* cache callback name lookup
5811 * (if not done yet, i.e. it's the first error) */
5812 if (known_errorHandler==-1) {
5813 if ((errors==NULL) || (!strcmp(errors, "strict")))
5814 known_errorHandler = 1;
5815 else if (!strcmp(errors, "replace"))
5816 known_errorHandler = 2;
5817 else if (!strcmp(errors, "ignore"))
5818 known_errorHandler = 3;
5819 else if (!strcmp(errors, "xmlcharrefreplace"))
5820 known_errorHandler = 4;
5821 else
5822 known_errorHandler = 0;
5823 }
5824 switch (known_errorHandler) {
5825 case 1: /* strict */
5826 raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005827 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005828 case 2: /* replace */
5829 /* No need to check for space, this is a 1:1 replacement */
5830 for (coll = collstart; coll<collend; ++coll)
5831 *str++ = '?';
5832 /* fall through */
5833 case 3: /* ignore */
5834 p = collend;
5835 break;
5836 case 4: /* xmlcharrefreplace */
5837 /* generate replacement (temporarily (mis)uses p) */
5838 for (p = collstart; p < collend; ++p) {
5839 char buffer[2+29+1+1];
5840 char *cp;
5841 sprintf(buffer, "&#%d;", (int)*p);
5842 if (charmaptranslate_makespace(&res, &str,
5843 (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
5844 goto onError;
5845 for (cp = buffer; *cp; ++cp)
5846 *str++ = *cp;
5847 }
5848 p = collend;
5849 break;
5850 default:
5851 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
5852 reason, startp, size, &exc,
5853 collstart-startp, collend-startp, &newpos);
5854 if (repunicode == NULL)
5855 goto onError;
5856 /* generate replacement */
5857 repsize = PyUnicode_GET_SIZE(repunicode);
5858 if (charmaptranslate_makespace(&res, &str,
5859 (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
5860 Py_DECREF(repunicode);
5861 goto onError;
5862 }
5863 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
5864 *str++ = *uni2;
5865 p = startp + newpos;
5866 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00005867 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005868 }
5869 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005870 /* Resize if we allocated to much */
5871 respos = str-PyUnicode_AS_UNICODE(res);
Walter Dörwald4894c302003-10-24 14:25:28 +00005872 if (respos<PyUnicode_GET_SIZE(res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005873 if (PyUnicode_Resize(&res, respos) < 0)
5874 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005875 }
5876 Py_XDECREF(exc);
5877 Py_XDECREF(errorHandler);
5878 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005881 Py_XDECREF(res);
5882 Py_XDECREF(exc);
5883 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 return NULL;
5885}
5886
5887PyObject *PyUnicode_Translate(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00005888 PyObject *mapping,
5889 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890{
5891 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00005892
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 str = PyUnicode_FromObject(str);
5894 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005895 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896 result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
Benjamin Peterson29060642009-01-31 22:14:21 +00005897 PyUnicode_GET_SIZE(str),
5898 mapping,
5899 errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005900 Py_DECREF(str);
5901 return result;
Tim Petersced69f82003-09-16 20:30:58 +00005902
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904 Py_XDECREF(str);
5905 return NULL;
5906}
Tim Petersced69f82003-09-16 20:30:58 +00005907
Guido van Rossum9e896b32000-04-05 20:11:21 +00005908/* --- Decimal Encoder ---------------------------------------------------- */
5909
5910int PyUnicode_EncodeDecimal(Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005911 Py_ssize_t length,
5912 char *output,
5913 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00005914{
5915 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005916 PyObject *errorHandler = NULL;
5917 PyObject *exc = NULL;
5918 const char *encoding = "decimal";
5919 const char *reason = "invalid decimal Unicode string";
5920 /* the following variable is used for caching string comparisons
5921 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
5922 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005923
5924 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 PyErr_BadArgument();
5926 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00005927 }
5928
5929 p = s;
5930 end = s + length;
5931 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 register Py_UNICODE ch = *p;
5933 int decimal;
5934 PyObject *repunicode;
5935 Py_ssize_t repsize;
5936 Py_ssize_t newpos;
5937 Py_UNICODE *uni2;
5938 Py_UNICODE *collstart;
5939 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00005940
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00005942 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 ++p;
5944 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005945 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 decimal = Py_UNICODE_TODECIMAL(ch);
5947 if (decimal >= 0) {
5948 *output++ = '0' + decimal;
5949 ++p;
5950 continue;
5951 }
5952 if (0 < ch && ch < 256) {
5953 *output++ = (char)ch;
5954 ++p;
5955 continue;
5956 }
5957 /* All other characters are considered unencodable */
5958 collstart = p;
5959 collend = p+1;
5960 while (collend < end) {
5961 if ((0 < *collend && *collend < 256) ||
5962 !Py_UNICODE_ISSPACE(*collend) ||
5963 Py_UNICODE_TODECIMAL(*collend))
5964 break;
5965 }
5966 /* cache callback name lookup
5967 * (if not done yet, i.e. it's the first error) */
5968 if (known_errorHandler==-1) {
5969 if ((errors==NULL) || (!strcmp(errors, "strict")))
5970 known_errorHandler = 1;
5971 else if (!strcmp(errors, "replace"))
5972 known_errorHandler = 2;
5973 else if (!strcmp(errors, "ignore"))
5974 known_errorHandler = 3;
5975 else if (!strcmp(errors, "xmlcharrefreplace"))
5976 known_errorHandler = 4;
5977 else
5978 known_errorHandler = 0;
5979 }
5980 switch (known_errorHandler) {
5981 case 1: /* strict */
5982 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
5983 goto onError;
5984 case 2: /* replace */
5985 for (p = collstart; p < collend; ++p)
5986 *output++ = '?';
5987 /* fall through */
5988 case 3: /* ignore */
5989 p = collend;
5990 break;
5991 case 4: /* xmlcharrefreplace */
5992 /* generate replacement (temporarily (mis)uses p) */
5993 for (p = collstart; p < collend; ++p)
5994 output += sprintf(output, "&#%d;", (int)*p);
5995 p = collend;
5996 break;
5997 default:
5998 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
5999 encoding, reason, s, length, &exc,
6000 collstart-s, collend-s, &newpos);
6001 if (repunicode == NULL)
6002 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006003 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006004 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006005 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
6006 Py_DECREF(repunicode);
6007 goto onError;
6008 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 /* generate replacement */
6010 repsize = PyUnicode_GET_SIZE(repunicode);
6011 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
6012 Py_UNICODE ch = *uni2;
6013 if (Py_UNICODE_ISSPACE(ch))
6014 *output++ = ' ';
6015 else {
6016 decimal = Py_UNICODE_TODECIMAL(ch);
6017 if (decimal >= 0)
6018 *output++ = '0' + decimal;
6019 else if (0 < ch && ch < 256)
6020 *output++ = (char)ch;
6021 else {
6022 Py_DECREF(repunicode);
6023 raise_encode_exception(&exc, encoding,
6024 s, length, collstart-s, collend-s, reason);
6025 goto onError;
6026 }
6027 }
6028 }
6029 p = s + newpos;
6030 Py_DECREF(repunicode);
6031 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00006032 }
6033 /* 0-terminate the output string */
6034 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035 Py_XDECREF(exc);
6036 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006037 return 0;
6038
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006040 Py_XDECREF(exc);
6041 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00006042 return -1;
6043}
6044
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045/* --- Helpers ------------------------------------------------------------ */
6046
Eric Smith8c663262007-08-25 02:26:07 +00006047#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006048#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006049
Thomas Wouters477c8d52006-05-27 19:21:47 +00006050#include "stringlib/count.h"
6051#include "stringlib/find.h"
6052#include "stringlib/partition.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006053#include "stringlib/split.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00006054
Eric Smith5807c412008-05-11 21:00:57 +00006055#define _Py_InsertThousandsGrouping _PyUnicode_InsertThousandsGrouping
Eric Smitha3b1ac82009-04-03 14:45:06 +00006056#define _Py_InsertThousandsGroupingLocale _PyUnicode_InsertThousandsGroupingLocale
Eric Smith5807c412008-05-11 21:00:57 +00006057#include "stringlib/localeutil.h"
6058
Thomas Wouters477c8d52006-05-27 19:21:47 +00006059/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006060#define ADJUST_INDICES(start, end, len) \
6061 if (end > len) \
6062 end = len; \
6063 else if (end < 0) { \
6064 end += len; \
6065 if (end < 0) \
6066 end = 0; \
6067 } \
6068 if (start < 0) { \
6069 start += len; \
6070 if (start < 0) \
6071 start = 0; \
6072 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006073
Martin v. Löwis18e16552006-02-15 17:27:45 +00006074Py_ssize_t PyUnicode_Count(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006075 PyObject *substr,
6076 Py_ssize_t start,
6077 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006079 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006080 PyUnicodeObject* str_obj;
6081 PyUnicodeObject* sub_obj;
Tim Petersced69f82003-09-16 20:30:58 +00006082
Thomas Wouters477c8d52006-05-27 19:21:47 +00006083 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
6084 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006086 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
6087 if (!sub_obj) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 Py_DECREF(str_obj);
6089 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 }
Tim Petersced69f82003-09-16 20:30:58 +00006091
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006092 ADJUST_INDICES(start, end, str_obj->length);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006093 result = stringlib_count(
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006094 str_obj->str + start, end - start, sub_obj->str, sub_obj->length,
6095 PY_SSIZE_T_MAX
Thomas Wouters477c8d52006-05-27 19:21:47 +00006096 );
6097
6098 Py_DECREF(sub_obj);
6099 Py_DECREF(str_obj);
6100
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 return result;
6102}
6103
Martin v. Löwis18e16552006-02-15 17:27:45 +00006104Py_ssize_t PyUnicode_Find(PyObject *str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00006105 PyObject *sub,
6106 Py_ssize_t start,
6107 Py_ssize_t end,
6108 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006110 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006111
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112 str = PyUnicode_FromObject(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006113 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006115 sub = PyUnicode_FromObject(sub);
6116 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 Py_DECREF(str);
6118 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119 }
Tim Petersced69f82003-09-16 20:30:58 +00006120
Thomas Wouters477c8d52006-05-27 19:21:47 +00006121 if (direction > 0)
6122 result = stringlib_find_slice(
6123 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6124 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6125 start, end
6126 );
6127 else
6128 result = stringlib_rfind_slice(
6129 PyUnicode_AS_UNICODE(str), PyUnicode_GET_SIZE(str),
6130 PyUnicode_AS_UNICODE(sub), PyUnicode_GET_SIZE(sub),
6131 start, end
6132 );
6133
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006135 Py_DECREF(sub);
6136
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137 return result;
6138}
6139
Tim Petersced69f82003-09-16 20:30:58 +00006140static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006141int tailmatch(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006142 PyUnicodeObject *substring,
6143 Py_ssize_t start,
6144 Py_ssize_t end,
6145 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006146{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006147 if (substring->length == 0)
6148 return 1;
6149
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006150 ADJUST_INDICES(start, end, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 end -= substring->length;
6152 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154
6155 if (direction > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 if (Py_UNICODE_MATCH(self, end, substring))
6157 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158 } else {
6159 if (Py_UNICODE_MATCH(self, start, substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 }
6162
6163 return 0;
6164}
6165
Martin v. Löwis18e16552006-02-15 17:27:45 +00006166Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 PyObject *substr,
6168 Py_ssize_t start,
6169 Py_ssize_t end,
6170 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006172 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00006173
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 str = PyUnicode_FromObject(str);
6175 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006177 substr = PyUnicode_FromObject(substr);
6178 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 Py_DECREF(str);
6180 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181 }
Tim Petersced69f82003-09-16 20:30:58 +00006182
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 (PyUnicodeObject *)substr,
6185 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 Py_DECREF(str);
6187 Py_DECREF(substr);
6188 return result;
6189}
6190
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191/* Apply fixfct filter to the Unicode object self and return a
6192 reference to the modified object */
6193
Tim Petersced69f82003-09-16 20:30:58 +00006194static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195PyObject *fixup(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006196 int (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197{
6198
6199 PyUnicodeObject *u;
6200
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006201 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006203 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006204
6205 Py_UNICODE_COPY(u->str, self->str, self->length);
6206
Tim Peters7a29bd52001-09-12 03:03:31 +00006207 if (!fixfct(u) && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006208 /* fixfct should return TRUE if it modified the buffer. If
6209 FALSE, return a reference to the original buffer instead
6210 (to save space, not time) */
6211 Py_INCREF(self);
6212 Py_DECREF(u);
6213 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214 }
6215 return (PyObject*) u;
6216}
6217
Tim Petersced69f82003-09-16 20:30:58 +00006218static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219int fixupper(PyUnicodeObject *self)
6220{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006221 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222 Py_UNICODE *s = self->str;
6223 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006224
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006226 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006227
Benjamin Peterson29060642009-01-31 22:14:21 +00006228 ch = Py_UNICODE_TOUPPER(*s);
6229 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 *s = ch;
6232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 s++;
6234 }
6235
6236 return status;
6237}
6238
Tim Petersced69f82003-09-16 20:30:58 +00006239static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240int fixlower(PyUnicodeObject *self)
6241{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006242 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 Py_UNICODE *s = self->str;
6244 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006245
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 while (len-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006247 register Py_UNICODE ch;
Tim Petersced69f82003-09-16 20:30:58 +00006248
Benjamin Peterson29060642009-01-31 22:14:21 +00006249 ch = Py_UNICODE_TOLOWER(*s);
6250 if (ch != *s) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006251 status = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006252 *s = ch;
6253 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006254 s++;
6255 }
6256
6257 return status;
6258}
6259
Tim Petersced69f82003-09-16 20:30:58 +00006260static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006261int fixswapcase(PyUnicodeObject *self)
6262{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006263 Py_ssize_t len = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006264 Py_UNICODE *s = self->str;
6265 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006266
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267 while (len-- > 0) {
6268 if (Py_UNICODE_ISUPPER(*s)) {
6269 *s = Py_UNICODE_TOLOWER(*s);
6270 status = 1;
6271 } else if (Py_UNICODE_ISLOWER(*s)) {
6272 *s = Py_UNICODE_TOUPPER(*s);
6273 status = 1;
6274 }
6275 s++;
6276 }
6277
6278 return status;
6279}
6280
Tim Petersced69f82003-09-16 20:30:58 +00006281static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282int fixcapitalize(PyUnicodeObject *self)
6283{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006284 Py_ssize_t len = self->length;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006285 Py_UNICODE *s = self->str;
6286 int status = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006287
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006288 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 return 0;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006290 if (Py_UNICODE_ISLOWER(*s)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 *s = Py_UNICODE_TOUPPER(*s);
6292 status = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00006294 s++;
6295 while (--len > 0) {
6296 if (Py_UNICODE_ISUPPER(*s)) {
6297 *s = Py_UNICODE_TOLOWER(*s);
6298 status = 1;
6299 }
6300 s++;
6301 }
6302 return status;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303}
6304
6305static
6306int fixtitle(PyUnicodeObject *self)
6307{
6308 register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
6309 register Py_UNICODE *e;
6310 int previous_is_cased;
6311
6312 /* Shortcut for single character strings */
6313 if (PyUnicode_GET_SIZE(self) == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006314 Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
6315 if (*p != ch) {
6316 *p = ch;
6317 return 1;
6318 }
6319 else
6320 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006321 }
Tim Petersced69f82003-09-16 20:30:58 +00006322
Guido van Rossumd57fd912000-03-10 22:53:23 +00006323 e = p + PyUnicode_GET_SIZE(self);
6324 previous_is_cased = 0;
6325 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006326 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00006327
Benjamin Peterson29060642009-01-31 22:14:21 +00006328 if (previous_is_cased)
6329 *p = Py_UNICODE_TOLOWER(ch);
6330 else
6331 *p = Py_UNICODE_TOTITLE(ch);
Tim Petersced69f82003-09-16 20:30:58 +00006332
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 if (Py_UNICODE_ISLOWER(ch) ||
6334 Py_UNICODE_ISUPPER(ch) ||
6335 Py_UNICODE_ISTITLE(ch))
6336 previous_is_cased = 1;
6337 else
6338 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006339 }
6340 return 1;
6341}
6342
Tim Peters8ce9f162004-08-27 01:49:32 +00006343PyObject *
6344PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345{
Skip Montanaro6543b452004-09-16 03:28:13 +00006346 const Py_UNICODE blank = ' ';
6347 const Py_UNICODE *sep = &blank;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006348 Py_ssize_t seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006349 PyUnicodeObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00006350 Py_UNICODE *res_p; /* pointer to free byte in res's string area */
6351 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006352 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
6353 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00006354 PyObject *item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006355 Py_ssize_t sz, i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006356
Tim Peters05eba1f2004-08-27 21:32:02 +00006357 fseq = PySequence_Fast(seq, "");
6358 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006359 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00006360 }
6361
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006362 /* NOTE: the following code can't call back into Python code,
6363 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00006364 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006365
Tim Peters05eba1f2004-08-27 21:32:02 +00006366 seqlen = PySequence_Fast_GET_SIZE(fseq);
6367 /* If empty sequence, return u"". */
6368 if (seqlen == 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006369 res = _PyUnicode_New(0); /* empty sequence; return u"" */
6370 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00006371 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006372 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00006373 /* If singleton sequence with an exact Unicode, return that. */
6374 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006375 item = items[0];
6376 if (PyUnicode_CheckExact(item)) {
6377 Py_INCREF(item);
6378 res = (PyUnicodeObject *)item;
6379 goto Done;
6380 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006381 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006382 else {
6383 /* Set up sep and seplen */
6384 if (separator == NULL) {
6385 sep = &blank;
6386 seplen = 1;
Tim Peters05eba1f2004-08-27 21:32:02 +00006387 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006388 else {
6389 if (!PyUnicode_Check(separator)) {
6390 PyErr_Format(PyExc_TypeError,
6391 "separator: expected str instance,"
6392 " %.80s found",
6393 Py_TYPE(separator)->tp_name);
6394 goto onError;
6395 }
6396 sep = PyUnicode_AS_UNICODE(separator);
6397 seplen = PyUnicode_GET_SIZE(separator);
Tim Peters05eba1f2004-08-27 21:32:02 +00006398 }
6399 }
6400
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006401 /* There are at least two things to join, or else we have a subclass
6402 * of str in the sequence.
6403 * Do a pre-pass to figure out the total amount of space we'll
6404 * need (sz), and see whether all argument are strings.
6405 */
6406 sz = 0;
6407 for (i = 0; i < seqlen; i++) {
6408 const Py_ssize_t old_sz = sz;
6409 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 if (!PyUnicode_Check(item)) {
6411 PyErr_Format(PyExc_TypeError,
6412 "sequence item %zd: expected str instance,"
6413 " %.80s found",
6414 i, Py_TYPE(item)->tp_name);
6415 goto onError;
6416 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006417 sz += PyUnicode_GET_SIZE(item);
6418 if (i != 0)
6419 sz += seplen;
6420 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
6421 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006423 goto onError;
6424 }
6425 }
Tim Petersced69f82003-09-16 20:30:58 +00006426
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006427 res = _PyUnicode_New(sz);
6428 if (res == NULL)
6429 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00006430
Antoine Pitrouaf14b792008-08-07 21:50:41 +00006431 /* Catenate everything. */
6432 res_p = PyUnicode_AS_UNICODE(res);
6433 for (i = 0; i < seqlen; ++i) {
6434 Py_ssize_t itemlen;
6435 item = items[i];
6436 itemlen = PyUnicode_GET_SIZE(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 /* Copy item, and maybe the separator. */
6438 if (i) {
6439 Py_UNICODE_COPY(res_p, sep, seplen);
6440 res_p += seplen;
6441 }
6442 Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
6443 res_p += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00006444 }
Tim Peters8ce9f162004-08-27 01:49:32 +00006445
Benjamin Peterson29060642009-01-31 22:14:21 +00006446 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00006447 Py_DECREF(fseq);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006448 return (PyObject *)res;
6449
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00006451 Py_DECREF(fseq);
Tim Peters8ce9f162004-08-27 01:49:32 +00006452 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006453 return NULL;
6454}
6455
Tim Petersced69f82003-09-16 20:30:58 +00006456static
6457PyUnicodeObject *pad(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 Py_ssize_t left,
6459 Py_ssize_t right,
6460 Py_UNICODE fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461{
6462 PyUnicodeObject *u;
6463
6464 if (left < 0)
6465 left = 0;
6466 if (right < 0)
6467 right = 0;
6468
Tim Peters7a29bd52001-09-12 03:03:31 +00006469 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006470 Py_INCREF(self);
6471 return self;
6472 }
6473
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006474 if (left > PY_SSIZE_T_MAX - self->length ||
6475 right > PY_SSIZE_T_MAX - (left + self->length)) {
6476 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
6477 return NULL;
6478 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479 u = _PyUnicode_New(left + self->length + right);
6480 if (u) {
6481 if (left)
6482 Py_UNICODE_FILL(u->str, fill, left);
6483 Py_UNICODE_COPY(u->str + left, self->str, self->length);
6484 if (right)
6485 Py_UNICODE_FILL(u->str + left + self->length, fill, right);
6486 }
6487
6488 return u;
6489}
6490
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006491PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006492{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006493 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494
6495 string = PyUnicode_FromObject(string);
6496 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006498
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006499 list = stringlib_splitlines(
6500 (PyObject*) string, PyUnicode_AS_UNICODE(string),
6501 PyUnicode_GET_SIZE(string), keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502
6503 Py_DECREF(string);
6504 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006505}
6506
Tim Petersced69f82003-09-16 20:30:58 +00006507static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508PyObject *split(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 PyUnicodeObject *substring,
6510 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006513 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006514
Guido van Rossumd57fd912000-03-10 22:53:23 +00006515 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006516 return stringlib_split_whitespace(
6517 (PyObject*) self, self->str, self->length, maxcount
6518 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006520 return stringlib_split(
6521 (PyObject*) self, self->str, self->length,
6522 substring->str, substring->length,
6523 maxcount
6524 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525}
6526
Tim Petersced69f82003-09-16 20:30:58 +00006527static
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006528PyObject *rsplit(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 PyUnicodeObject *substring,
6530 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006531{
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006532 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006533 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006534
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006535 if (substring == NULL)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006536 return stringlib_rsplit_whitespace(
6537 (PyObject*) self, self->str, self->length, maxcount
6538 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006539
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006540 return stringlib_rsplit(
6541 (PyObject*) self, self->str, self->length,
6542 substring->str, substring->length,
6543 maxcount
6544 );
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00006545}
6546
6547static
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548PyObject *replace(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 PyUnicodeObject *str1,
6550 PyUnicodeObject *str2,
6551 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006552{
6553 PyUnicodeObject *u;
6554
6555 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006556 maxcount = PY_SSIZE_T_MAX;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006557 else if (maxcount == 0 || self->length == 0)
6558 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006559
Thomas Wouters477c8d52006-05-27 19:21:47 +00006560 if (str1->length == str2->length) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00006561 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006562 /* same length */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006563 if (str1->length == 0)
6564 goto nothing;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006565 if (str1->length == 1) {
6566 /* replace characters */
6567 Py_UNICODE u1, u2;
6568 if (!findchar(self->str, self->length, str1->str[0]))
6569 goto nothing;
6570 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6571 if (!u)
6572 return NULL;
6573 Py_UNICODE_COPY(u->str, self->str, self->length);
6574 u1 = str1->str[0];
6575 u2 = str2->str[0];
6576 for (i = 0; i < u->length; i++)
6577 if (u->str[i] == u1) {
6578 if (--maxcount < 0)
6579 break;
6580 u->str[i] = u2;
6581 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006582 } else {
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006583 i = stringlib_find(
6584 self->str, self->length, str1->str, str1->length, 0
Guido van Rossumd57fd912000-03-10 22:53:23 +00006585 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00006586 if (i < 0)
6587 goto nothing;
6588 u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
6589 if (!u)
6590 return NULL;
6591 Py_UNICODE_COPY(u->str, self->str, self->length);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006592
6593 /* change everything in-place, starting with this one */
6594 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6595 i += str1->length;
6596
6597 while ( --maxcount > 0) {
6598 i = stringlib_find(self->str+i, self->length-i,
6599 str1->str, str1->length,
6600 i);
6601 if (i == -1)
6602 break;
6603 Py_UNICODE_COPY(u->str+i, str2->str, str2->length);
6604 i += str1->length;
6605 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006607 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006608
6609 Py_ssize_t n, i, j, e;
6610 Py_ssize_t product, new_size, delta;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006611 Py_UNICODE *p;
6612
6613 /* replace strings */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006614 n = stringlib_count(self->str, self->length, str1->str, str1->length,
6615 maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006616 if (n == 0)
6617 goto nothing;
6618 /* new_size = self->length + n * (str2->length - str1->length)); */
6619 delta = (str2->length - str1->length);
6620 if (delta == 0) {
6621 new_size = self->length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006623 product = n * (str2->length - str1->length);
6624 if ((product / (str2->length - str1->length)) != n) {
6625 PyErr_SetString(PyExc_OverflowError,
6626 "replace string is too long");
6627 return NULL;
6628 }
6629 new_size = self->length + product;
6630 if (new_size < 0) {
6631 PyErr_SetString(PyExc_OverflowError,
6632 "replace string is too long");
6633 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006634 }
6635 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00006636 u = _PyUnicode_New(new_size);
6637 if (!u)
6638 return NULL;
6639 i = 0;
6640 p = u->str;
6641 e = self->length - str1->length;
6642 if (str1->length > 0) {
6643 while (n-- > 0) {
6644 /* look for next match */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00006645 j = stringlib_find(self->str+i, self->length-i,
6646 str1->str, str1->length,
6647 i);
6648 if (j == -1)
6649 break;
6650 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006651 /* copy unchanged part [i:j] */
6652 Py_UNICODE_COPY(p, self->str+i, j-i);
6653 p += j - i;
6654 }
6655 /* copy substitution string */
6656 if (str2->length > 0) {
6657 Py_UNICODE_COPY(p, str2->str, str2->length);
6658 p += str2->length;
6659 }
6660 i = j + str1->length;
6661 }
6662 if (i < self->length)
6663 /* copy tail [i:] */
6664 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6665 } else {
6666 /* interleave */
6667 while (n > 0) {
6668 Py_UNICODE_COPY(p, str2->str, str2->length);
6669 p += str2->length;
6670 if (--n <= 0)
6671 break;
6672 *p++ = self->str[i++];
6673 }
6674 Py_UNICODE_COPY(p, self->str+i, self->length-i);
6675 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006676 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006677 return (PyObject *) u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00006678
Benjamin Peterson29060642009-01-31 22:14:21 +00006679 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00006680 /* nothing to replace; return original string (when possible) */
6681 if (PyUnicode_CheckExact(self)) {
6682 Py_INCREF(self);
6683 return (PyObject *) self;
6684 }
6685 return PyUnicode_FromUnicode(self->str, self->length);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686}
6687
6688/* --- Unicode Object Methods --------------------------------------------- */
6689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006690PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006691 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692\n\
6693Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006694characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695
6696static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006697unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006699 return fixup(self, fixtitle);
6700}
6701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006702PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006703 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006704\n\
6705Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00006706have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707
6708static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006709unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006711 return fixup(self, fixcapitalize);
6712}
6713
6714#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006715PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006717\n\
6718Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006719normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720
6721static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00006722unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006723{
6724 PyObject *list;
6725 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006726 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006727
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728 /* Split into words */
6729 list = split(self, NULL, -1);
6730 if (!list)
6731 return NULL;
6732
6733 /* Capitalize each word */
6734 for (i = 0; i < PyList_GET_SIZE(list); i++) {
6735 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737 if (item == NULL)
6738 goto onError;
6739 Py_DECREF(PyList_GET_ITEM(list, i));
6740 PyList_SET_ITEM(list, i, item);
6741 }
6742
6743 /* Join the words to form a new string */
6744 item = PyUnicode_Join(NULL, list);
6745
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006747 Py_DECREF(list);
6748 return (PyObject *)item;
6749}
6750#endif
6751
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006752/* Argument converter. Coerces to a single unicode character */
6753
6754static int
6755convert_uc(PyObject *obj, void *addr)
6756{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006757 Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
6758 PyObject *uniobj;
6759 Py_UNICODE *unistr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006760
Benjamin Peterson14339b62009-01-31 16:36:08 +00006761 uniobj = PyUnicode_FromObject(obj);
6762 if (uniobj == NULL) {
6763 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006765 return 0;
6766 }
6767 if (PyUnicode_GET_SIZE(uniobj) != 1) {
6768 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006770 Py_DECREF(uniobj);
6771 return 0;
6772 }
6773 unistr = PyUnicode_AS_UNICODE(uniobj);
6774 *fillcharloc = unistr[0];
6775 Py_DECREF(uniobj);
6776 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006777}
6778
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00006779PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00006780 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00006782Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006783done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784
6785static PyObject *
6786unicode_center(PyUnicodeObject *self, PyObject *args)
6787{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006788 Py_ssize_t marg, left;
6789 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006790 Py_UNICODE fillchar = ' ';
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791
Thomas Woutersde017742006-02-16 19:34:37 +00006792 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793 return NULL;
6794
Tim Peters7a29bd52001-09-12 03:03:31 +00006795 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006796 Py_INCREF(self);
6797 return (PyObject*) self;
6798 }
6799
6800 marg = width - self->length;
6801 left = marg / 2 + (marg & width & 1);
6802
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00006803 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804}
6805
Marc-André Lemburge5034372000-08-08 08:04:29 +00006806#if 0
6807
6808/* This code should go into some future Unicode collation support
6809 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00006810 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00006811
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006812/* speedy UTF-16 code point order comparison */
6813/* gleaned from: */
6814/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
6815
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006816static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006817{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006818 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00006819 0, 0, 0, 0, 0, 0, 0, 0,
6820 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00006821 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006822};
6823
Guido van Rossumd57fd912000-03-10 22:53:23 +00006824static int
6825unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6826{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006827 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006828
Guido van Rossumd57fd912000-03-10 22:53:23 +00006829 Py_UNICODE *s1 = str1->str;
6830 Py_UNICODE *s2 = str2->str;
6831
6832 len1 = str1->length;
6833 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006834
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006836 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006837
6838 c1 = *s1++;
6839 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00006840
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 if (c1 > (1<<11) * 26)
6842 c1 += utf16Fixup[c1>>11];
6843 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006844 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006845 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00006846
6847 if (c1 != c2)
6848 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00006849
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00006850 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006851 }
6852
6853 return (len1 < len2) ? -1 : (len1 != len2);
6854}
6855
Marc-André Lemburge5034372000-08-08 08:04:29 +00006856#else
6857
6858static int
6859unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
6860{
Martin v. Löwis18e16552006-02-15 17:27:45 +00006861 register Py_ssize_t len1, len2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006862
6863 Py_UNICODE *s1 = str1->str;
6864 Py_UNICODE *s2 = str2->str;
6865
6866 len1 = str1->length;
6867 len2 = str2->length;
Tim Petersced69f82003-09-16 20:30:58 +00006868
Marc-André Lemburge5034372000-08-08 08:04:29 +00006869 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00006870 Py_UNICODE c1, c2;
Marc-André Lemburge5034372000-08-08 08:04:29 +00006871
Fredrik Lundh45714e92001-06-26 16:39:36 +00006872 c1 = *s1++;
6873 c2 = *s2++;
6874
6875 if (c1 != c2)
6876 return (c1 < c2) ? -1 : 1;
6877
Marc-André Lemburge5034372000-08-08 08:04:29 +00006878 len1--; len2--;
6879 }
6880
6881 return (len1 < len2) ? -1 : (len1 != len2);
6882}
6883
6884#endif
6885
Guido van Rossumd57fd912000-03-10 22:53:23 +00006886int PyUnicode_Compare(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006888{
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006889 if (PyUnicode_Check(left) && PyUnicode_Check(right))
6890 return unicode_compare((PyUnicodeObject *)left,
6891 (PyUnicodeObject *)right);
Guido van Rossum09dc34f2007-05-04 04:17:33 +00006892 PyErr_Format(PyExc_TypeError,
6893 "Can't compare %.100s and %.100s",
6894 left->ob_type->tp_name,
6895 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006896 return -1;
6897}
6898
Martin v. Löwis5b222132007-06-10 09:51:05 +00006899int
6900PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
6901{
6902 int i;
6903 Py_UNICODE *id;
6904 assert(PyUnicode_Check(uni));
6905 id = PyUnicode_AS_UNICODE(uni);
6906 /* Compare Unicode string and source character set string */
6907 for (i = 0; id[i] && str[i]; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 if (id[i] != str[i])
6909 return ((int)id[i] < (int)str[i]) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00006910 /* This check keeps Python strings that end in '\0' from comparing equal
6911 to C strings identical up to that point. */
Benjamin Petersona23831f2010-04-25 21:54:00 +00006912 if (PyUnicode_GET_SIZE(uni) != i || id[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006913 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006914 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00006915 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00006916 return 0;
6917}
6918
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006919
Benjamin Peterson29060642009-01-31 22:14:21 +00006920#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00006921 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006922
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006923PyObject *PyUnicode_RichCompare(PyObject *left,
6924 PyObject *right,
6925 int op)
6926{
6927 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006928
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006929 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
6930 PyObject *v;
6931 if (((PyUnicodeObject *) left)->length !=
6932 ((PyUnicodeObject *) right)->length) {
6933 if (op == Py_EQ) {
6934 Py_INCREF(Py_False);
6935 return Py_False;
6936 }
6937 if (op == Py_NE) {
6938 Py_INCREF(Py_True);
6939 return Py_True;
6940 }
6941 }
6942 if (left == right)
6943 result = 0;
6944 else
6945 result = unicode_compare((PyUnicodeObject *)left,
6946 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006947
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006948 /* Convert the return value to a Boolean */
6949 switch (op) {
6950 case Py_EQ:
6951 v = TEST_COND(result == 0);
6952 break;
6953 case Py_NE:
6954 v = TEST_COND(result != 0);
6955 break;
6956 case Py_LE:
6957 v = TEST_COND(result <= 0);
6958 break;
6959 case Py_GE:
6960 v = TEST_COND(result >= 0);
6961 break;
6962 case Py_LT:
6963 v = TEST_COND(result == -1);
6964 break;
6965 case Py_GT:
6966 v = TEST_COND(result == 1);
6967 break;
6968 default:
6969 PyErr_BadArgument();
6970 return NULL;
6971 }
6972 Py_INCREF(v);
6973 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006974 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006975
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00006976 Py_INCREF(Py_NotImplemented);
6977 return Py_NotImplemented;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00006978}
6979
Guido van Rossum403d68b2000-03-13 15:55:09 +00006980int PyUnicode_Contains(PyObject *container,
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00006982{
Thomas Wouters477c8d52006-05-27 19:21:47 +00006983 PyObject *str, *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006984 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00006985
6986 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00006987 sub = PyUnicode_FromObject(element);
6988 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006989 PyErr_Format(PyExc_TypeError,
6990 "'in <string>' requires string as left operand, not %s",
6991 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00006992 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00006993 }
6994
Thomas Wouters477c8d52006-05-27 19:21:47 +00006995 str = PyUnicode_FromObject(container);
6996 if (!str) {
6997 Py_DECREF(sub);
6998 return -1;
6999 }
7000
7001 result = stringlib_contains_obj(str, sub);
7002
7003 Py_DECREF(str);
7004 Py_DECREF(sub);
7005
Guido van Rossum403d68b2000-03-13 15:55:09 +00007006 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00007007}
7008
Guido van Rossumd57fd912000-03-10 22:53:23 +00007009/* Concat to string or Unicode object giving a new Unicode object. */
7010
7011PyObject *PyUnicode_Concat(PyObject *left,
Benjamin Peterson29060642009-01-31 22:14:21 +00007012 PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007013{
7014 PyUnicodeObject *u = NULL, *v = NULL, *w;
7015
7016 /* Coerce the two arguments */
7017 u = (PyUnicodeObject *)PyUnicode_FromObject(left);
7018 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007019 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007020 v = (PyUnicodeObject *)PyUnicode_FromObject(right);
7021 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007023
7024 /* Shortcuts */
7025 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007026 Py_DECREF(v);
7027 return (PyObject *)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007028 }
7029 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007030 Py_DECREF(u);
7031 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007032 }
7033
7034 /* Concat the two Unicode strings */
7035 w = _PyUnicode_New(u->length + v->length);
7036 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007037 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007038 Py_UNICODE_COPY(w->str, u->str, u->length);
7039 Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
7040
7041 Py_DECREF(u);
7042 Py_DECREF(v);
7043 return (PyObject *)w;
7044
Benjamin Peterson29060642009-01-31 22:14:21 +00007045 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007046 Py_XDECREF(u);
7047 Py_XDECREF(v);
7048 return NULL;
7049}
7050
Walter Dörwald1ab83302007-05-18 17:15:44 +00007051void
7052PyUnicode_Append(PyObject **pleft, PyObject *right)
7053{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007054 PyObject *new;
7055 if (*pleft == NULL)
7056 return;
7057 if (right == NULL || !PyUnicode_Check(*pleft)) {
7058 Py_DECREF(*pleft);
7059 *pleft = NULL;
7060 return;
7061 }
7062 new = PyUnicode_Concat(*pleft, right);
7063 Py_DECREF(*pleft);
7064 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00007065}
7066
7067void
7068PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
7069{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007070 PyUnicode_Append(pleft, right);
7071 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00007072}
7073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007074PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007075 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007076\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00007077Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007078string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007079interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007080
7081static PyObject *
7082unicode_count(PyUnicodeObject *self, PyObject *args)
7083{
7084 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007085 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007086 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007087 PyObject *result;
7088
Guido van Rossumb8872e62000-05-09 14:14:27 +00007089 if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091 return NULL;
7092
7093 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007094 (PyObject *)substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007095 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007096 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007097
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007098 ADJUST_INDICES(start, end, self->length);
Christian Heimes217cfd12007-12-02 14:31:20 +00007099 result = PyLong_FromSsize_t(
Thomas Wouters477c8d52006-05-27 19:21:47 +00007100 stringlib_count(self->str + start, end - start,
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007101 substring->str, substring->length,
7102 PY_SSIZE_T_MAX)
Thomas Wouters477c8d52006-05-27 19:21:47 +00007103 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007104
7105 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007106
Guido van Rossumd57fd912000-03-10 22:53:23 +00007107 return result;
7108}
7109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007110PyDoc_STRVAR(encode__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007111 "S.encode([encoding[, errors]]) -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007112\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00007113Encode S using the codec registered for encoding. encoding defaults\n\
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007114to the default encoding. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00007115handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007116a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
7117'xmlcharrefreplace' as well as any other name registered with\n\
7118codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007119
7120static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00007121unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007122{
Benjamin Peterson308d6372009-09-18 21:42:35 +00007123 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00007124 char *encoding = NULL;
7125 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007126 PyObject *v;
Guido van Rossum35d94282007-08-27 18:20:11 +00007127
Benjamin Peterson308d6372009-09-18 21:42:35 +00007128 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
7129 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007130 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00007131 v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007132 if (v == NULL)
7133 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00007134 if (!PyBytes_Check(v)) {
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007135 PyErr_Format(PyExc_TypeError,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00007136 "encoder did not return a bytes object "
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007137 "(type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00007138 Py_TYPE(v)->tp_name);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007139 Py_DECREF(v);
7140 return NULL;
7141 }
7142 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007143
Benjamin Peterson29060642009-01-31 22:14:21 +00007144 onError:
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00007145 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00007146}
7147
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007148PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007149 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007150\n\
7151Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007152If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007153
7154static PyObject*
7155unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
7156{
7157 Py_UNICODE *e;
7158 Py_UNICODE *p;
7159 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007160 Py_UNICODE *qe;
7161 Py_ssize_t i, j, incr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007162 PyUnicodeObject *u;
7163 int tabsize = 8;
7164
7165 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007166 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007167
Thomas Wouters7e474022000-07-16 12:04:32 +00007168 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007169 i = 0; /* chars up to and including most recent \n or \r */
7170 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
7171 e = self->str + self->length; /* end of input */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007172 for (p = self->str; p < e; p++)
7173 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007174 if (tabsize > 0) {
7175 incr = tabsize - (j % tabsize); /* cannot overflow */
7176 if (j > PY_SSIZE_T_MAX - incr)
7177 goto overflow1;
7178 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007179 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007180 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007181 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 if (j > PY_SSIZE_T_MAX - 1)
7183 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007184 j++;
7185 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007186 if (i > PY_SSIZE_T_MAX - j)
7187 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007188 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007189 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007190 }
7191 }
7192
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007193 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00007194 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007195
Guido van Rossumd57fd912000-03-10 22:53:23 +00007196 /* Second pass: create output string and fill it */
7197 u = _PyUnicode_New(i + j);
7198 if (!u)
7199 return NULL;
7200
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007201 j = 0; /* same as in first pass */
7202 q = u->str; /* next output char */
7203 qe = u->str + u->length; /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007204
7205 for (p = self->str; p < e; p++)
7206 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00007207 if (tabsize > 0) {
7208 i = tabsize - (j % tabsize);
7209 j += i;
7210 while (i--) {
7211 if (q >= qe)
7212 goto overflow2;
7213 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007214 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007215 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007216 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007217 else {
7218 if (q >= qe)
7219 goto overflow2;
7220 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007221 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007222 if (*p == '\n' || *p == '\r')
7223 j = 0;
7224 }
7225
7226 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00007227
7228 overflow2:
7229 Py_DECREF(u);
7230 overflow1:
7231 PyErr_SetString(PyExc_OverflowError, "new string is too long");
7232 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007233}
7234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007235PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007236 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007237\n\
7238Return the lowest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00007239such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007240arguments start and end are interpreted as in slice notation.\n\
7241\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007242Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007243
7244static PyObject *
7245unicode_find(PyUnicodeObject *self, PyObject *args)
7246{
Thomas Wouters477c8d52006-05-27 19:21:47 +00007247 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00007248 Py_ssize_t start;
7249 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007250 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007251
Christian Heimes9cd17752007-11-18 19:35:23 +00007252 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007254
Thomas Wouters477c8d52006-05-27 19:21:47 +00007255 result = stringlib_find_slice(
7256 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7257 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7258 start, end
7259 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007260
7261 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007262
Christian Heimes217cfd12007-12-02 14:31:20 +00007263 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007264}
7265
7266static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00007267unicode_getitem(PyUnicodeObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007268{
7269 if (index < 0 || index >= self->length) {
7270 PyErr_SetString(PyExc_IndexError, "string index out of range");
7271 return NULL;
7272 }
7273
7274 return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
7275}
7276
Guido van Rossumc2504932007-09-18 19:42:40 +00007277/* Believe it or not, this produces the same value for ASCII strings
7278 as string_hash(). */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007279static long
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00007280unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007281{
Guido van Rossumc2504932007-09-18 19:42:40 +00007282 Py_ssize_t len;
7283 Py_UNICODE *p;
7284 long x;
7285
7286 if (self->hash != -1)
7287 return self->hash;
Christian Heimes90aa7642007-12-19 02:45:37 +00007288 len = Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007289 p = self->str;
7290 x = *p << 7;
7291 while (--len >= 0)
7292 x = (1000003*x) ^ *p++;
Christian Heimes90aa7642007-12-19 02:45:37 +00007293 x ^= Py_SIZE(self);
Guido van Rossumc2504932007-09-18 19:42:40 +00007294 if (x == -1)
7295 x = -2;
7296 self->hash = x;
7297 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007298}
7299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007300PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007301 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007302\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007303Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007304
7305static PyObject *
7306unicode_index(PyUnicodeObject *self, PyObject *args)
7307{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007308 Py_ssize_t result;
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;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007312
Christian Heimes9cd17752007-11-18 19:35:23 +00007313 if (!_ParseTupleFinds(args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007314 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007315
Thomas Wouters477c8d52006-05-27 19:21:47 +00007316 result = stringlib_find_slice(
7317 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
7318 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
7319 start, end
7320 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00007321
7322 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007323
Guido van Rossumd57fd912000-03-10 22:53:23 +00007324 if (result < 0) {
7325 PyErr_SetString(PyExc_ValueError, "substring not found");
7326 return NULL;
7327 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007328
Christian Heimes217cfd12007-12-02 14:31:20 +00007329 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007330}
7331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007332PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007333 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007334\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007335Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007336at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007337
7338static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007339unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007340{
7341 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7342 register const Py_UNICODE *e;
7343 int cased;
7344
Guido van Rossumd57fd912000-03-10 22:53:23 +00007345 /* Shortcut for single character strings */
7346 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007347 return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007348
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007349 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007350 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007351 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007352
Guido van Rossumd57fd912000-03-10 22:53:23 +00007353 e = p + PyUnicode_GET_SIZE(self);
7354 cased = 0;
7355 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007356 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007357
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
7359 return PyBool_FromLong(0);
7360 else if (!cased && Py_UNICODE_ISLOWER(ch))
7361 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007362 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007363 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007364}
7365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007366PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007367 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007368\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007369Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007370at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007371
7372static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007373unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007374{
7375 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7376 register const Py_UNICODE *e;
7377 int cased;
7378
Guido van Rossumd57fd912000-03-10 22:53:23 +00007379 /* Shortcut for single character strings */
7380 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007381 return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007382
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007383 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007384 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007385 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007386
Guido van Rossumd57fd912000-03-10 22:53:23 +00007387 e = p + PyUnicode_GET_SIZE(self);
7388 cased = 0;
7389 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007390 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007391
Benjamin Peterson29060642009-01-31 22:14:21 +00007392 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
7393 return PyBool_FromLong(0);
7394 else if (!cased && Py_UNICODE_ISUPPER(ch))
7395 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007396 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007397 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007398}
7399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007400PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007401 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007402\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007403Return True if S is a titlecased string and there is at least one\n\
7404character in S, i.e. upper- and titlecase characters may only\n\
7405follow uncased characters and lowercase characters only cased ones.\n\
7406Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007407
7408static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007409unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007410{
7411 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7412 register const Py_UNICODE *e;
7413 int cased, previous_is_cased;
7414
Guido van Rossumd57fd912000-03-10 22:53:23 +00007415 /* Shortcut for single character strings */
7416 if (PyUnicode_GET_SIZE(self) == 1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007417 return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
7418 (Py_UNICODE_ISUPPER(*p) != 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007420 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007421 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007423
Guido van Rossumd57fd912000-03-10 22:53:23 +00007424 e = p + PyUnicode_GET_SIZE(self);
7425 cased = 0;
7426 previous_is_cased = 0;
7427 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 register const Py_UNICODE ch = *p;
Tim Petersced69f82003-09-16 20:30:58 +00007429
Benjamin Peterson29060642009-01-31 22:14:21 +00007430 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
7431 if (previous_is_cased)
7432 return PyBool_FromLong(0);
7433 previous_is_cased = 1;
7434 cased = 1;
7435 }
7436 else if (Py_UNICODE_ISLOWER(ch)) {
7437 if (!previous_is_cased)
7438 return PyBool_FromLong(0);
7439 previous_is_cased = 1;
7440 cased = 1;
7441 }
7442 else
7443 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007444 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007445 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007446}
7447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007448PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007449 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007450\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007451Return True if all characters in S are whitespace\n\
7452and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007453
7454static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007455unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007456{
7457 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7458 register const Py_UNICODE *e;
7459
Guido van Rossumd57fd912000-03-10 22:53:23 +00007460 /* Shortcut for single character strings */
7461 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 Py_UNICODE_ISSPACE(*p))
7463 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007464
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007465 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007466 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007467 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007468
Guido van Rossumd57fd912000-03-10 22:53:23 +00007469 e = p + PyUnicode_GET_SIZE(self);
7470 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007471 if (!Py_UNICODE_ISSPACE(*p))
7472 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007473 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007474 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475}
7476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007477PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007478 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007479\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007480Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007481and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007482
7483static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007484unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007485{
7486 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7487 register const Py_UNICODE *e;
7488
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007489 /* Shortcut for single character strings */
7490 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007491 Py_UNICODE_ISALPHA(*p))
7492 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007493
7494 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007495 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007496 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007497
7498 e = p + PyUnicode_GET_SIZE(self);
7499 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007500 if (!Py_UNICODE_ISALPHA(*p))
7501 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007502 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007503 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007504}
7505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007506PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007507 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007508\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007509Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007510and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007511
7512static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007513unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007514{
7515 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7516 register const Py_UNICODE *e;
7517
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007518 /* Shortcut for single character strings */
7519 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 Py_UNICODE_ISALNUM(*p))
7521 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007522
7523 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007524 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007526
7527 e = p + PyUnicode_GET_SIZE(self);
7528 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 if (!Py_UNICODE_ISALNUM(*p))
7530 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007531 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007532 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +00007533}
7534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007535PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007536 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007537\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007538Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007539False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007540
7541static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007542unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007543{
7544 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7545 register const Py_UNICODE *e;
7546
Guido van Rossumd57fd912000-03-10 22:53:23 +00007547 /* Shortcut for single character strings */
7548 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007549 Py_UNICODE_ISDECIMAL(*p))
7550 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007552 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007553 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007554 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007555
Guido van Rossumd57fd912000-03-10 22:53:23 +00007556 e = p + PyUnicode_GET_SIZE(self);
7557 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007558 if (!Py_UNICODE_ISDECIMAL(*p))
7559 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007560 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007561 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562}
7563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007564PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00007567Return True if all characters in S are digits\n\
7568and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007569
7570static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007571unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572{
7573 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7574 register const Py_UNICODE *e;
7575
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576 /* Shortcut for single character strings */
7577 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 Py_UNICODE_ISDIGIT(*p))
7579 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007580
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007581 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007582 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007583 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007584
Guido van Rossumd57fd912000-03-10 22:53:23 +00007585 e = p + PyUnicode_GET_SIZE(self);
7586 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007587 if (!Py_UNICODE_ISDIGIT(*p))
7588 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007589 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007590 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591}
7592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007593PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007595\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00007596Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007597False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007598
7599static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007600unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007601{
7602 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7603 register const Py_UNICODE *e;
7604
Guido van Rossumd57fd912000-03-10 22:53:23 +00007605 /* Shortcut for single character strings */
7606 if (PyUnicode_GET_SIZE(self) == 1 &&
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 Py_UNICODE_ISNUMERIC(*p))
7608 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007609
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007610 /* Special case for empty strings */
Martin v. Löwisdea59e52006-01-05 10:00:36 +00007611 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00007613
Guido van Rossumd57fd912000-03-10 22:53:23 +00007614 e = p + PyUnicode_GET_SIZE(self);
7615 for (; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007616 if (!Py_UNICODE_ISNUMERIC(*p))
7617 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007618 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00007619 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007620}
7621
Martin v. Löwis47383402007-08-15 07:32:56 +00007622int
7623PyUnicode_IsIdentifier(PyObject *self)
7624{
7625 register const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self);
7626 register const Py_UNICODE *e;
7627
7628 /* Special case for empty strings */
7629 if (PyUnicode_GET_SIZE(self) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007630 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007631
7632 /* PEP 3131 says that the first character must be in
7633 XID_Start and subsequent characters in XID_Continue,
7634 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +00007635 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +00007636 letters, digits, underscore). However, given the current
7637 definition of XID_Start and XID_Continue, it is sufficient
7638 to check just for these, except that _ must be allowed
7639 as starting an identifier. */
7640 if (!_PyUnicode_IsXidStart(*p) && *p != 0x5F /* LOW LINE */)
7641 return 0;
7642
7643 e = p + PyUnicode_GET_SIZE(self);
7644 for (p++; p < e; p++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007645 if (!_PyUnicode_IsXidContinue(*p))
7646 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +00007647 }
7648 return 1;
7649}
7650
7651PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007652 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +00007653\n\
7654Return True if S is a valid identifier according\n\
7655to the language definition.");
7656
7657static PyObject*
7658unicode_isidentifier(PyObject *self)
7659{
7660 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
7661}
7662
Georg Brandl559e5d72008-06-11 18:37:52 +00007663PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007664 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +00007665\n\
7666Return True if all characters in S are considered\n\
7667printable in repr() or S is empty, False otherwise.");
7668
7669static PyObject*
7670unicode_isprintable(PyObject *self)
7671{
7672 register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
7673 register const Py_UNICODE *e;
7674
7675 /* Shortcut for single character strings */
7676 if (PyUnicode_GET_SIZE(self) == 1 && Py_UNICODE_ISPRINTABLE(*p)) {
7677 Py_RETURN_TRUE;
7678 }
7679
7680 e = p + PyUnicode_GET_SIZE(self);
7681 for (; p < e; p++) {
7682 if (!Py_UNICODE_ISPRINTABLE(*p)) {
7683 Py_RETURN_FALSE;
7684 }
7685 }
7686 Py_RETURN_TRUE;
7687}
7688
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007689PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +00007690 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691\n\
7692Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +00007693iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007694
7695static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007696unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007697{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007698 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007699}
7700
Martin v. Löwis18e16552006-02-15 17:27:45 +00007701static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +00007702unicode_length(PyUnicodeObject *self)
7703{
7704 return self->length;
7705}
7706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007707PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00007710Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007711done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007712
7713static PyObject *
7714unicode_ljust(PyUnicodeObject *self, PyObject *args)
7715{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007716 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007717 Py_UNICODE fillchar = ' ';
7718
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007719 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007720 return NULL;
7721
Tim Peters7a29bd52001-09-12 03:03:31 +00007722 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723 Py_INCREF(self);
7724 return (PyObject*) self;
7725 }
7726
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00007727 return (PyObject*) pad(self, 0, width - self->length, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728}
7729
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007730PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007731 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007732\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007733Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734
7735static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00007736unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007737{
Guido van Rossumd57fd912000-03-10 22:53:23 +00007738 return fixup(self, fixlower);
7739}
7740
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007741#define LEFTSTRIP 0
7742#define RIGHTSTRIP 1
7743#define BOTHSTRIP 2
7744
7745/* Arrays indexed by above */
7746static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
7747
7748#define STRIPNAME(i) (stripformat[i]+3)
7749
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007750/* externally visible for str.strip(unicode) */
7751PyObject *
7752_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
7753{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007754 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7755 Py_ssize_t len = PyUnicode_GET_SIZE(self);
7756 Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
7757 Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
7758 Py_ssize_t i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007759
Benjamin Peterson29060642009-01-31 22:14:21 +00007760 BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +00007761
Benjamin Peterson14339b62009-01-31 16:36:08 +00007762 i = 0;
7763 if (striptype != RIGHTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
7765 i++;
7766 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007767 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007768
Benjamin Peterson14339b62009-01-31 16:36:08 +00007769 j = len;
7770 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007771 do {
7772 j--;
7773 } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
7774 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007775 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007776
Benjamin Peterson14339b62009-01-31 16:36:08 +00007777 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 Py_INCREF(self);
7779 return (PyObject*)self;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007780 }
7781 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007782 return PyUnicode_FromUnicode(s+i, j-i);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007783}
7784
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785
7786static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007787do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007788{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007789 Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
7790 Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007791
Benjamin Peterson14339b62009-01-31 16:36:08 +00007792 i = 0;
7793 if (striptype != RIGHTSTRIP) {
7794 while (i < len && Py_UNICODE_ISSPACE(s[i])) {
7795 i++;
7796 }
7797 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007798
Benjamin Peterson14339b62009-01-31 16:36:08 +00007799 j = len;
7800 if (striptype != LEFTSTRIP) {
7801 do {
7802 j--;
7803 } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
7804 j++;
7805 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007806
Benjamin Peterson14339b62009-01-31 16:36:08 +00007807 if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
7808 Py_INCREF(self);
7809 return (PyObject*)self;
7810 }
7811 else
7812 return PyUnicode_FromUnicode(s+i, j-i);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007813}
7814
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007815
7816static PyObject *
7817do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
7818{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007819 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007820
Benjamin Peterson14339b62009-01-31 16:36:08 +00007821 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
7822 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007823
Benjamin Peterson14339b62009-01-31 16:36:08 +00007824 if (sep != NULL && sep != Py_None) {
7825 if (PyUnicode_Check(sep))
7826 return _PyUnicode_XStrip(self, striptype, sep);
7827 else {
7828 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 "%s arg must be None or str",
7830 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +00007831 return NULL;
7832 }
7833 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007834
Benjamin Peterson14339b62009-01-31 16:36:08 +00007835 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007836}
7837
7838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007839PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007840 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007841\n\
7842Return a copy of the string S with leading and trailing\n\
7843whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007844If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007845
7846static PyObject *
7847unicode_strip(PyUnicodeObject *self, PyObject *args)
7848{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007849 if (PyTuple_GET_SIZE(args) == 0)
7850 return do_strip(self, BOTHSTRIP); /* Common case */
7851 else
7852 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007853}
7854
7855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007856PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007858\n\
7859Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007860If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007861
7862static PyObject *
7863unicode_lstrip(PyUnicodeObject *self, PyObject *args)
7864{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865 if (PyTuple_GET_SIZE(args) == 0)
7866 return do_strip(self, LEFTSTRIP); /* Common case */
7867 else
7868 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007869}
7870
7871
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007872PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00007873 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007874\n\
7875Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00007876If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007877
7878static PyObject *
7879unicode_rstrip(PyUnicodeObject *self, PyObject *args)
7880{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007881 if (PyTuple_GET_SIZE(args) == 0)
7882 return do_strip(self, RIGHTSTRIP); /* Common case */
7883 else
7884 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00007885}
7886
7887
Guido van Rossumd57fd912000-03-10 22:53:23 +00007888static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +00007889unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007890{
7891 PyUnicodeObject *u;
7892 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007893 Py_ssize_t nchars;
Tim Peters8f422462000-09-09 06:13:41 +00007894 size_t nbytes;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007895
Georg Brandl222de0f2009-04-12 12:01:50 +00007896 if (len < 1) {
7897 Py_INCREF(unicode_empty);
7898 return (PyObject *)unicode_empty;
7899 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007900
Tim Peters7a29bd52001-09-12 03:03:31 +00007901 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00007902 /* no repeat, return original string */
7903 Py_INCREF(str);
7904 return (PyObject*) str;
7905 }
Tim Peters8f422462000-09-09 06:13:41 +00007906
7907 /* ensure # of chars needed doesn't overflow int and # of bytes
7908 * needed doesn't overflow size_t
7909 */
7910 nchars = len * str->length;
Georg Brandl222de0f2009-04-12 12:01:50 +00007911 if (nchars / len != str->length) {
Tim Peters8f422462000-09-09 06:13:41 +00007912 PyErr_SetString(PyExc_OverflowError,
7913 "repeated string is too long");
7914 return NULL;
7915 }
7916 nbytes = (nchars + 1) * sizeof(Py_UNICODE);
7917 if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
7918 PyErr_SetString(PyExc_OverflowError,
7919 "repeated string is too long");
7920 return NULL;
7921 }
7922 u = _PyUnicode_New(nchars);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007923 if (!u)
7924 return NULL;
7925
7926 p = u->str;
7927
Georg Brandl222de0f2009-04-12 12:01:50 +00007928 if (str->length == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00007929 Py_UNICODE_FILL(p, str->str[0], len);
7930 } else {
Georg Brandl222de0f2009-04-12 12:01:50 +00007931 Py_ssize_t done = str->length; /* number of characters copied this far */
7932 Py_UNICODE_COPY(p, str->str, str->length);
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 while (done < nchars) {
Christian Heimescc47b052008-03-25 14:56:36 +00007934 Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007935 Py_UNICODE_COPY(p+done, p, n);
7936 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007938 }
7939
7940 return (PyObject*) u;
7941}
7942
7943PyObject *PyUnicode_Replace(PyObject *obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007944 PyObject *subobj,
7945 PyObject *replobj,
7946 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007947{
7948 PyObject *self;
7949 PyObject *str1;
7950 PyObject *str2;
7951 PyObject *result;
7952
7953 self = PyUnicode_FromObject(obj);
7954 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956 str1 = PyUnicode_FromObject(subobj);
7957 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 Py_DECREF(self);
7959 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007960 }
7961 str2 = PyUnicode_FromObject(replobj);
7962 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 Py_DECREF(self);
7964 Py_DECREF(str1);
7965 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007966 }
Tim Petersced69f82003-09-16 20:30:58 +00007967 result = replace((PyUnicodeObject *)self,
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 (PyUnicodeObject *)str1,
7969 (PyUnicodeObject *)str2,
7970 maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 Py_DECREF(self);
7972 Py_DECREF(str1);
7973 Py_DECREF(str2);
7974 return result;
7975}
7976
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007977PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +00007978 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00007979\n\
7980Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +00007981old replaced by new. If the optional argument count is\n\
7982given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983
7984static PyObject*
7985unicode_replace(PyUnicodeObject *self, PyObject *args)
7986{
7987 PyUnicodeObject *str1;
7988 PyUnicodeObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007989 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 PyObject *result;
7991
Martin v. Löwis18e16552006-02-15 17:27:45 +00007992 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00007993 return NULL;
7994 str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
7995 if (str1 == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007996 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00007998 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 Py_DECREF(str1);
8000 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +00008001 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002
8003 result = replace(self, str1, str2, maxcount);
8004
8005 Py_DECREF(str1);
8006 Py_DECREF(str2);
8007 return result;
8008}
8009
8010static
8011PyObject *unicode_repr(PyObject *unicode)
8012{
Walter Dörwald79e913e2007-05-12 11:08:06 +00008013 PyObject *repr;
Walter Dörwald1ab83302007-05-18 17:15:44 +00008014 Py_UNICODE *p;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008015 Py_UNICODE *s = PyUnicode_AS_UNICODE(unicode);
8016 Py_ssize_t size = PyUnicode_GET_SIZE(unicode);
8017
8018 /* XXX(nnorwitz): rather than over-allocating, it would be
8019 better to choose a different scheme. Perhaps scan the
8020 first N-chars of the string and allocate based on that size.
8021 */
8022 /* Initial allocation is based on the longest-possible unichr
8023 escape.
8024
8025 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
8026 unichr, so in this case it's the longest unichr escape. In
8027 narrow (UTF-16) builds this is five chars per source unichr
8028 since there are two unichrs in the surrogate pair, so in narrow
8029 (UTF-16) builds it's not the longest unichr escape.
8030
8031 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
8032 so in the narrow (UTF-16) build case it's the longest unichr
8033 escape.
8034 */
8035
Walter Dörwald1ab83302007-05-18 17:15:44 +00008036 repr = PyUnicode_FromUnicode(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 2 /* quotes */
Walter Dörwald79e913e2007-05-12 11:08:06 +00008038#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 + 10*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008040#else
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 + 6*size
Walter Dörwald79e913e2007-05-12 11:08:06 +00008042#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00008043 + 1);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008044 if (repr == NULL)
8045 return NULL;
8046
Walter Dörwald1ab83302007-05-18 17:15:44 +00008047 p = PyUnicode_AS_UNICODE(repr);
Walter Dörwald79e913e2007-05-12 11:08:06 +00008048
8049 /* Add quote */
8050 *p++ = (findchar(s, size, '\'') &&
8051 !findchar(s, size, '"')) ? '"' : '\'';
8052 while (size-- > 0) {
8053 Py_UNICODE ch = *s++;
8054
8055 /* Escape quotes and backslashes */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008056 if ((ch == PyUnicode_AS_UNICODE(repr)[0]) || (ch == '\\')) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008057 *p++ = '\\';
Walter Dörwald1ab83302007-05-18 17:15:44 +00008058 *p++ = ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00008059 continue;
8060 }
8061
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008063 if (ch == '\t') {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008064 *p++ = '\\';
8065 *p++ = 't';
8066 }
8067 else if (ch == '\n') {
8068 *p++ = '\\';
8069 *p++ = 'n';
8070 }
8071 else if (ch == '\r') {
8072 *p++ = '\\';
8073 *p++ = 'r';
8074 }
8075
8076 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +00008077 else if (ch < ' ' || ch == 0x7F) {
Walter Dörwald79e913e2007-05-12 11:08:06 +00008078 *p++ = '\\';
8079 *p++ = 'x';
8080 *p++ = hexdigits[(ch >> 4) & 0x000F];
8081 *p++ = hexdigits[ch & 0x000F];
8082 }
8083
Georg Brandl559e5d72008-06-11 18:37:52 +00008084 /* Copy ASCII characters as-is */
8085 else if (ch < 0x7F) {
8086 *p++ = ch;
8087 }
8088
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +00008090 else {
8091 Py_UCS4 ucs = ch;
8092
8093#ifndef Py_UNICODE_WIDE
8094 Py_UNICODE ch2 = 0;
8095 /* Get code point from surrogate pair */
8096 if (size > 0) {
8097 ch2 = *s;
8098 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
Benjamin Peterson29060642009-01-31 22:14:21 +00008099 && ch2 <= 0xDFFF) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008100 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 + 0x00010000;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008102 s++;
Georg Brandl559e5d72008-06-11 18:37:52 +00008103 size--;
8104 }
8105 }
8106#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +00008108 (categories Z* and C* except ASCII space)
8109 */
8110 if (!Py_UNICODE_ISPRINTABLE(ucs)) {
8111 /* Map 8-bit characters to '\xhh' */
8112 if (ucs <= 0xff) {
8113 *p++ = '\\';
8114 *p++ = 'x';
8115 *p++ = hexdigits[(ch >> 4) & 0x000F];
8116 *p++ = hexdigits[ch & 0x000F];
8117 }
8118 /* Map 21-bit characters to '\U00xxxxxx' */
8119 else if (ucs >= 0x10000) {
8120 *p++ = '\\';
8121 *p++ = 'U';
8122 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
8123 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
8124 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
8125 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
8126 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
8127 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
8128 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
8129 *p++ = hexdigits[ucs & 0x0000000F];
8130 }
8131 /* Map 16-bit characters to '\uxxxx' */
8132 else {
8133 *p++ = '\\';
8134 *p++ = 'u';
8135 *p++ = hexdigits[(ucs >> 12) & 0x000F];
8136 *p++ = hexdigits[(ucs >> 8) & 0x000F];
8137 *p++ = hexdigits[(ucs >> 4) & 0x000F];
8138 *p++ = hexdigits[ucs & 0x000F];
8139 }
8140 }
8141 /* Copy characters as-is */
8142 else {
8143 *p++ = ch;
8144#ifndef Py_UNICODE_WIDE
8145 if (ucs >= 0x10000)
8146 *p++ = ch2;
8147#endif
8148 }
8149 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00008150 }
8151 /* Add quote */
Walter Dörwald1ab83302007-05-18 17:15:44 +00008152 *p++ = PyUnicode_AS_UNICODE(repr)[0];
Walter Dörwald79e913e2007-05-12 11:08:06 +00008153
8154 *p = '\0';
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00008155 PyUnicode_Resize(&repr, p - PyUnicode_AS_UNICODE(repr));
Walter Dörwald79e913e2007-05-12 11:08:06 +00008156 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008157}
8158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008159PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008161\n\
8162Return the highest index in S where substring sub is found,\n\
Guido van Rossum806c2462007-08-06 23:33:07 +00008163such that sub is contained within s[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008164arguments start and end are interpreted as in slice notation.\n\
8165\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008166Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167
8168static PyObject *
8169unicode_rfind(PyUnicodeObject *self, PyObject *args)
8170{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008171 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008172 Py_ssize_t start;
8173 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008174 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008175
Christian Heimes9cd17752007-11-18 19:35:23 +00008176 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008177 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008178
Thomas Wouters477c8d52006-05-27 19:21:47 +00008179 result = stringlib_rfind_slice(
8180 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8181 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8182 start, end
8183 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008184
8185 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008186
Christian Heimes217cfd12007-12-02 14:31:20 +00008187 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008188}
8189
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008190PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008192\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008193Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008194
8195static PyObject *
8196unicode_rindex(PyUnicodeObject *self, PyObject *args)
8197{
Thomas Wouters477c8d52006-05-27 19:21:47 +00008198 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00008199 Py_ssize_t start;
8200 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008201 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202
Christian Heimes9cd17752007-11-18 19:35:23 +00008203 if (!_ParseTupleFinds(args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205
Thomas Wouters477c8d52006-05-27 19:21:47 +00008206 result = stringlib_rfind_slice(
8207 PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
8208 PyUnicode_AS_UNICODE(substring), PyUnicode_GET_SIZE(substring),
8209 start, end
8210 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008211
8212 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008213
Guido van Rossumd57fd912000-03-10 22:53:23 +00008214 if (result < 0) {
8215 PyErr_SetString(PyExc_ValueError, "substring not found");
8216 return NULL;
8217 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008218 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008219}
8220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008221PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008223\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008224Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008225done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008226
8227static PyObject *
8228unicode_rjust(PyUnicodeObject *self, PyObject *args)
8229{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008230 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008231 Py_UNICODE fillchar = ' ';
8232
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008233 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008234 return NULL;
8235
Tim Peters7a29bd52001-09-12 03:03:31 +00008236 if (self->length >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237 Py_INCREF(self);
8238 return (PyObject*) self;
8239 }
8240
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00008241 return (PyObject*) pad(self, width - self->length, 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008242}
8243
Guido van Rossumd57fd912000-03-10 22:53:23 +00008244PyObject *PyUnicode_Split(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 PyObject *sep,
8246 Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008247{
8248 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008249
Guido van Rossumd57fd912000-03-10 22:53:23 +00008250 s = PyUnicode_FromObject(s);
8251 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 if (sep != NULL) {
8254 sep = PyUnicode_FromObject(sep);
8255 if (sep == NULL) {
8256 Py_DECREF(s);
8257 return NULL;
8258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008259 }
8260
8261 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8262
8263 Py_DECREF(s);
8264 Py_XDECREF(sep);
8265 return result;
8266}
8267
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008268PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008270\n\
8271Return a list of the words in S, using sep as the\n\
8272delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00008273splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00008274whitespace string is a separator and empty strings are\n\
8275removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276
8277static PyObject*
8278unicode_split(PyUnicodeObject *self, PyObject *args)
8279{
8280 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008281 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282
Martin v. Löwis18e16552006-02-15 17:27:45 +00008283 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284 return NULL;
8285
8286 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008287 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008288 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008292}
8293
Thomas Wouters477c8d52006-05-27 19:21:47 +00008294PyObject *
8295PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
8296{
8297 PyObject* str_obj;
8298 PyObject* sep_obj;
8299 PyObject* out;
8300
8301 str_obj = PyUnicode_FromObject(str_in);
8302 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008304 sep_obj = PyUnicode_FromObject(sep_in);
8305 if (!sep_obj) {
8306 Py_DECREF(str_obj);
8307 return NULL;
8308 }
8309
8310 out = stringlib_partition(
8311 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8312 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8313 );
8314
8315 Py_DECREF(sep_obj);
8316 Py_DECREF(str_obj);
8317
8318 return out;
8319}
8320
8321
8322PyObject *
8323PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
8324{
8325 PyObject* str_obj;
8326 PyObject* sep_obj;
8327 PyObject* out;
8328
8329 str_obj = PyUnicode_FromObject(str_in);
8330 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008332 sep_obj = PyUnicode_FromObject(sep_in);
8333 if (!sep_obj) {
8334 Py_DECREF(str_obj);
8335 return NULL;
8336 }
8337
8338 out = stringlib_rpartition(
8339 str_obj, PyUnicode_AS_UNICODE(str_obj), PyUnicode_GET_SIZE(str_obj),
8340 sep_obj, PyUnicode_AS_UNICODE(sep_obj), PyUnicode_GET_SIZE(sep_obj)
8341 );
8342
8343 Py_DECREF(sep_obj);
8344 Py_DECREF(str_obj);
8345
8346 return out;
8347}
8348
8349PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008351\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008352Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008353the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008354found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008355
8356static PyObject*
8357unicode_partition(PyUnicodeObject *self, PyObject *separator)
8358{
8359 return PyUnicode_Partition((PyObject *)self, separator);
8360}
8361
8362PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +00008363 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008364\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +00008365Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00008366the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00008367separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00008368
8369static PyObject*
8370unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
8371{
8372 return PyUnicode_RPartition((PyObject *)self, separator);
8373}
8374
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008375PyObject *PyUnicode_RSplit(PyObject *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 PyObject *sep,
8377 Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008378{
8379 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008380
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008381 s = PyUnicode_FromObject(s);
8382 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008383 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 if (sep != NULL) {
8385 sep = PyUnicode_FromObject(sep);
8386 if (sep == NULL) {
8387 Py_DECREF(s);
8388 return NULL;
8389 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008390 }
8391
8392 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
8393
8394 Py_DECREF(s);
8395 Py_XDECREF(sep);
8396 return result;
8397}
8398
8399PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008401\n\
8402Return a list of the words in S, using sep as the\n\
8403delimiter string, starting at the end of the string and\n\
8404working to the front. If maxsplit is given, at most maxsplit\n\
8405splits are done. If sep is not specified, any whitespace string\n\
8406is a separator.");
8407
8408static PyObject*
8409unicode_rsplit(PyUnicodeObject *self, PyObject *args)
8410{
8411 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008412 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008413
Martin v. Löwis18e16552006-02-15 17:27:45 +00008414 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008415 return NULL;
8416
8417 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008419 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008421 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008422 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008423}
8424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008425PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427\n\
8428Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +00008429Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008430is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431
8432static PyObject*
8433unicode_splitlines(PyUnicodeObject *self, PyObject *args)
8434{
Guido van Rossum86662912000-04-11 15:38:46 +00008435 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008436
Guido van Rossum86662912000-04-11 15:38:46 +00008437 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008438 return NULL;
8439
Guido van Rossum86662912000-04-11 15:38:46 +00008440 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008441}
8442
8443static
Guido van Rossumf15a29f2007-05-04 00:41:39 +00008444PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445{
Walter Dörwald346737f2007-05-31 10:44:43 +00008446 if (PyUnicode_CheckExact(self)) {
8447 Py_INCREF(self);
8448 return self;
8449 } else
8450 /* Subtype -- return genuine unicode string with the same value. */
8451 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(self),
8452 PyUnicode_GET_SIZE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +00008453}
8454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008455PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008457\n\
8458Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008459and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008460
8461static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008462unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464 return fixup(self, fixswapcase);
8465}
8466
Georg Brandlceee0772007-11-27 23:48:05 +00008467PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008469\n\
8470Return a translation table usable for str.translate().\n\
8471If there is only one argument, it must be a dictionary mapping Unicode\n\
8472ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008473Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +00008474If there are two arguments, they must be strings of equal length, and\n\
8475in the resulting dictionary, each character in x will be mapped to the\n\
8476character at the same position in y. If there is a third argument, it\n\
8477must be a string, whose characters will be mapped to None in the result.");
8478
8479static PyObject*
8480unicode_maketrans(PyUnicodeObject *null, PyObject *args)
8481{
8482 PyObject *x, *y = NULL, *z = NULL;
8483 PyObject *new = NULL, *key, *value;
8484 Py_ssize_t i = 0;
8485 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008486
Georg Brandlceee0772007-11-27 23:48:05 +00008487 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
8488 return NULL;
8489 new = PyDict_New();
8490 if (!new)
8491 return NULL;
8492 if (y != NULL) {
8493 /* x must be a string too, of equal length */
8494 Py_ssize_t ylen = PyUnicode_GET_SIZE(y);
8495 if (!PyUnicode_Check(x)) {
8496 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
8497 "be a string if there is a second argument");
8498 goto err;
8499 }
8500 if (PyUnicode_GET_SIZE(x) != ylen) {
8501 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
8502 "arguments must have equal length");
8503 goto err;
8504 }
8505 /* create entries for translating chars in x to those in y */
8506 for (i = 0; i < PyUnicode_GET_SIZE(x); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008507 key = PyLong_FromLong(PyUnicode_AS_UNICODE(x)[i]);
8508 value = PyLong_FromLong(PyUnicode_AS_UNICODE(y)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008509 if (!key || !value)
8510 goto err;
8511 res = PyDict_SetItem(new, key, value);
8512 Py_DECREF(key);
8513 Py_DECREF(value);
8514 if (res < 0)
8515 goto err;
8516 }
8517 /* create entries for deleting chars in z */
8518 if (z != NULL) {
8519 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +00008520 key = PyLong_FromLong(PyUnicode_AS_UNICODE(z)[i]);
Georg Brandlceee0772007-11-27 23:48:05 +00008521 if (!key)
8522 goto err;
8523 res = PyDict_SetItem(new, key, Py_None);
8524 Py_DECREF(key);
8525 if (res < 0)
8526 goto err;
8527 }
8528 }
8529 } else {
8530 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +00008531 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008532 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
8533 "to maketrans it must be a dict");
8534 goto err;
8535 }
8536 /* copy entries into the new dict, converting string keys to int keys */
8537 while (PyDict_Next(x, &i, &key, &value)) {
8538 if (PyUnicode_Check(key)) {
8539 /* convert string keys to integer keys */
8540 PyObject *newkey;
8541 if (PyUnicode_GET_SIZE(key) != 1) {
8542 PyErr_SetString(PyExc_ValueError, "string keys in translate "
8543 "table must be of length 1");
8544 goto err;
8545 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008546 newkey = PyLong_FromLong(PyUnicode_AS_UNICODE(key)[0]);
Georg Brandlceee0772007-11-27 23:48:05 +00008547 if (!newkey)
8548 goto err;
8549 res = PyDict_SetItem(new, newkey, value);
8550 Py_DECREF(newkey);
8551 if (res < 0)
8552 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +00008553 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +00008554 /* just keep integer keys */
8555 if (PyDict_SetItem(new, key, value) < 0)
8556 goto err;
8557 } else {
8558 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
8559 "be strings or integers");
8560 goto err;
8561 }
8562 }
8563 }
8564 return new;
8565 err:
8566 Py_DECREF(new);
8567 return NULL;
8568}
8569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008570PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008572\n\
8573Return a copy of the string S, where all characters have been mapped\n\
8574through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00008575Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +00008576Unmapped characters are left untouched. Characters mapped to None\n\
8577are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008578
8579static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008580unicode_translate(PyUnicodeObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008581{
Georg Brandlceee0772007-11-27 23:48:05 +00008582 return PyUnicode_TranslateCharmap(self->str, self->length, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583}
8584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008585PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008588Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589
8590static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008591unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593 return fixup(self, fixupper);
8594}
8595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008596PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008598\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +00008599Pad a numeric string S with zeros on the left, to fill a field\n\
8600of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601
8602static PyObject *
8603unicode_zfill(PyUnicodeObject *self, PyObject *args)
8604{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008605 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008606 PyUnicodeObject *u;
8607
Martin v. Löwis18e16552006-02-15 17:27:45 +00008608 Py_ssize_t width;
8609 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610 return NULL;
8611
8612 if (self->length >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00008613 if (PyUnicode_CheckExact(self)) {
8614 Py_INCREF(self);
8615 return (PyObject*) self;
8616 }
8617 else
8618 return PyUnicode_FromUnicode(
8619 PyUnicode_AS_UNICODE(self),
8620 PyUnicode_GET_SIZE(self)
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00008622 }
8623
8624 fill = width - self->length;
8625
8626 u = pad(self, fill, 0, '0');
8627
Walter Dörwald068325e2002-04-15 13:36:47 +00008628 if (u == NULL)
8629 return NULL;
8630
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631 if (u->str[fill] == '+' || u->str[fill] == '-') {
8632 /* move sign to beginning of string */
8633 u->str[0] = u->str[fill];
8634 u->str[fill] = '0';
8635 }
8636
8637 return (PyObject*) u;
8638}
Guido van Rossumd57fd912000-03-10 22:53:23 +00008639
8640#if 0
8641static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008642unicode_freelistsize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643{
Christian Heimes2202f872008-02-06 14:31:34 +00008644 return PyLong_FromLong(numfree);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645}
8646#endif
8647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008648PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008651Return True if S starts with the specified prefix, False otherwise.\n\
8652With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008653With optional end, stop comparing S at that position.\n\
8654prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008655
8656static PyObject *
8657unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008659{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008660 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008661 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008662 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008663 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008664 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008665
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008666 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8668 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008669 if (PyTuple_Check(subobj)) {
8670 Py_ssize_t i;
8671 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8672 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008674 if (substring == NULL)
8675 return NULL;
8676 result = tailmatch(self, substring, start, end, -1);
8677 Py_DECREF(substring);
8678 if (result) {
8679 Py_RETURN_TRUE;
8680 }
8681 }
8682 /* nothing matched */
8683 Py_RETURN_FALSE;
8684 }
8685 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008688 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008689 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008690 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691}
8692
8693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00008694PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00008696\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00008697Return True if S ends with the specified suffix, False otherwise.\n\
8698With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008699With optional end, stop comparing S at that position.\n\
8700suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008701
8702static PyObject *
8703unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008705{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008706 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008708 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008709 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008710 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008711
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008712 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
8714 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008715 if (PyTuple_Check(subobj)) {
8716 Py_ssize_t i;
8717 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
8718 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008720 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008722 result = tailmatch(self, substring, start, end, +1);
8723 Py_DECREF(substring);
8724 if (result) {
8725 Py_RETURN_TRUE;
8726 }
8727 }
8728 Py_RETURN_FALSE;
8729 }
8730 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008731 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008734 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008735 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008736 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008737}
8738
Eric Smith8c663262007-08-25 02:26:07 +00008739#include "stringlib/string_format.h"
8740
8741PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008743\n\
8744");
8745
Eric Smith4a7d76d2008-05-30 18:10:19 +00008746static PyObject *
8747unicode__format__(PyObject* self, PyObject* args)
8748{
8749 PyObject *format_spec;
8750
8751 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
8752 return NULL;
8753
8754 return _PyUnicode_FormatAdvanced(self,
8755 PyUnicode_AS_UNICODE(format_spec),
8756 PyUnicode_GET_SIZE(format_spec));
8757}
8758
Eric Smith8c663262007-08-25 02:26:07 +00008759PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +00008761\n\
8762");
8763
8764static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008765unicode__sizeof__(PyUnicodeObject *v)
8766{
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00008767 return PyLong_FromSsize_t(sizeof(PyUnicodeObject) +
8768 sizeof(Py_UNICODE) * (v->length + 1));
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008769}
8770
8771PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008773
8774static PyObject *
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008775unicode_getnewargs(PyUnicodeObject *v)
8776{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008777 return Py_BuildValue("(u#)", v->str, v->length);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00008778}
8779
8780
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781static PyMethodDef unicode_methods[] = {
8782
8783 /* Order is according to common usage: often used methods should
8784 appear first, since lookup is done sequentially. */
8785
Benjamin Peterson308d6372009-09-18 21:42:35 +00008786 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008787 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
8788 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008789 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008790 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
8791 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
8792 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
8793 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
8794 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
8795 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
8796 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008797 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008798 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
8799 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
8800 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008801 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008802 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
8803 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
8804 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008805 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00008806 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008807 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00008808 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008809 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
8810 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
8811 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
8812 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
8813 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
8814 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
8815 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
8816 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
8817 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
8818 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
8819 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
8820 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
8821 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
8822 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +00008823 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +00008824 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008825 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +00008826 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +00008827 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Eric Smithf6db4092007-08-27 23:52:26 +00008828 {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
8829 {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
Georg Brandlceee0772007-11-27 23:48:05 +00008830 {"maketrans", (PyCFunction) unicode_maketrans,
8831 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +00008832 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +00008833#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008834 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835#endif
8836
8837#if 0
8838 /* This one is just used for debugging the implementation. */
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00008839 {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008840#endif
8841
Benjamin Peterson14339b62009-01-31 16:36:08 +00008842 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +00008843 {NULL, NULL}
8844};
8845
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008846static PyObject *
8847unicode_mod(PyObject *v, PyObject *w)
8848{
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 if (!PyUnicode_Check(v)) {
8850 Py_INCREF(Py_NotImplemented);
8851 return Py_NotImplemented;
8852 }
8853 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008854}
8855
8856static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008857 0, /*nb_add*/
8858 0, /*nb_subtract*/
8859 0, /*nb_multiply*/
8860 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +00008861};
8862
Guido van Rossumd57fd912000-03-10 22:53:23 +00008863static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008864 (lenfunc) unicode_length, /* sq_length */
8865 PyUnicode_Concat, /* sq_concat */
8866 (ssizeargfunc) unicode_repeat, /* sq_repeat */
8867 (ssizeargfunc) unicode_getitem, /* sq_item */
8868 0, /* sq_slice */
8869 0, /* sq_ass_item */
8870 0, /* sq_ass_slice */
8871 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +00008872};
8873
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008874static PyObject*
8875unicode_subscript(PyUnicodeObject* self, PyObject* item)
8876{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00008877 if (PyIndex_Check(item)) {
8878 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008879 if (i == -1 && PyErr_Occurred())
8880 return NULL;
8881 if (i < 0)
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008882 i += PyUnicode_GET_SIZE(self);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008883 return unicode_getitem(self, i);
8884 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00008885 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008886 Py_UNICODE* source_buf;
8887 Py_UNICODE* result_buf;
8888 PyObject* result;
8889
Martin v. Löwisdea59e52006-01-05 10:00:36 +00008890 if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008892 return NULL;
8893 }
8894
8895 if (slicelength <= 0) {
8896 return PyUnicode_FromUnicode(NULL, 0);
Thomas Woutersed03b412007-08-28 21:37:11 +00008897 } else if (start == 0 && step == 1 && slicelength == self->length &&
8898 PyUnicode_CheckExact(self)) {
8899 Py_INCREF(self);
8900 return (PyObject *)self;
8901 } else if (step == 1) {
8902 return PyUnicode_FromUnicode(self->str + start, slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008903 } else {
8904 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +00008905 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
8906 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +00008907
Benjamin Peterson29060642009-01-31 22:14:21 +00008908 if (result_buf == NULL)
8909 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008910
8911 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
8912 result_buf[i] = source_buf[cur];
8913 }
Tim Petersced69f82003-09-16 20:30:58 +00008914
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008915 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +00008916 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008917 return result;
8918 }
8919 } else {
8920 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
8921 return NULL;
8922 }
8923}
8924
8925static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008926 (lenfunc)unicode_length, /* mp_length */
8927 (binaryfunc)unicode_subscript, /* mp_subscript */
8928 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00008929};
8930
Guido van Rossumd57fd912000-03-10 22:53:23 +00008931
Guido van Rossumd57fd912000-03-10 22:53:23 +00008932/* Helpers for PyUnicode_Format() */
8933
8934static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00008935getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008936{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008937 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008938 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 (*p_argidx)++;
8940 if (arglen < 0)
8941 return args;
8942 else
8943 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944 }
8945 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +00008947 return NULL;
8948}
8949
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008950/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00008951
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008952static PyObject *
8953formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008954{
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008955 char *p;
8956 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008957 double x;
Tim Petersced69f82003-09-16 20:30:58 +00008958
Guido van Rossumd57fd912000-03-10 22:53:23 +00008959 x = PyFloat_AsDouble(v);
8960 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008961 return NULL;
8962
Guido van Rossumd57fd912000-03-10 22:53:23 +00008963 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008964 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +00008965
Eric Smith0923d1d2009-04-16 20:16:10 +00008966 p = PyOS_double_to_string(x, type, prec,
8967 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +00008968 if (p == NULL)
8969 return NULL;
8970 result = PyUnicode_FromStringAndSize(p, strlen(p));
Eric Smith0923d1d2009-04-16 20:16:10 +00008971 PyMem_Free(p);
8972 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008973}
8974
Tim Peters38fd5b62000-09-21 05:43:11 +00008975static PyObject*
8976formatlong(PyObject *val, int flags, int prec, int type)
8977{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008978 char *buf;
8979 int len;
8980 PyObject *str; /* temporary string object. */
8981 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +00008982
Benjamin Peterson14339b62009-01-31 16:36:08 +00008983 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
8984 if (!str)
8985 return NULL;
8986 result = PyUnicode_FromStringAndSize(buf, len);
8987 Py_DECREF(str);
8988 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +00008989}
8990
Guido van Rossumd57fd912000-03-10 22:53:23 +00008991static int
8992formatchar(Py_UNICODE *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00008993 size_t buflen,
8994 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008995{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00008996 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00008997 if (PyUnicode_Check(v)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008998 if (PyUnicode_GET_SIZE(v) == 1) {
8999 buf[0] = PyUnicode_AS_UNICODE(v)[0];
9000 buf[1] = '\0';
9001 return 1;
9002 }
9003#ifndef Py_UNICODE_WIDE
9004 if (PyUnicode_GET_SIZE(v) == 2) {
9005 /* Decode a valid surrogate pair */
9006 int c0 = PyUnicode_AS_UNICODE(v)[0];
9007 int c1 = PyUnicode_AS_UNICODE(v)[1];
9008 if (0xD800 <= c0 && c0 <= 0xDBFF &&
9009 0xDC00 <= c1 && c1 <= 0xDFFF) {
9010 buf[0] = c0;
9011 buf[1] = c1;
9012 buf[2] = '\0';
9013 return 2;
9014 }
9015 }
9016#endif
9017 goto onError;
9018 }
9019 else {
9020 /* Integer input truncated to a character */
9021 long x;
9022 x = PyLong_AsLong(v);
9023 if (x == -1 && PyErr_Occurred())
9024 goto onError;
9025
9026 if (x < 0 || x > 0x10ffff) {
9027 PyErr_SetString(PyExc_OverflowError,
9028 "%c arg not in range(0x110000)");
9029 return -1;
9030 }
9031
9032#ifndef Py_UNICODE_WIDE
9033 if (x > 0xffff) {
9034 x -= 0x10000;
9035 buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
9036 buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
9037 return 2;
9038 }
9039#endif
9040 buf[0] = (Py_UNICODE) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009041 buf[1] = '\0';
9042 return 1;
9043 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00009044
Benjamin Peterson29060642009-01-31 22:14:21 +00009045 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009046 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +00009048 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049}
9050
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009051/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009052 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009053*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009054#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00009055
Guido van Rossumd57fd912000-03-10 22:53:23 +00009056PyObject *PyUnicode_Format(PyObject *format,
Benjamin Peterson29060642009-01-31 22:14:21 +00009057 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009058{
9059 Py_UNICODE *fmt, *res;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009060 Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009061 int args_owned = 0;
9062 PyUnicodeObject *result = NULL;
9063 PyObject *dict = NULL;
9064 PyObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +00009065
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009067 PyErr_BadInternalCall();
9068 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069 }
9070 uformat = PyUnicode_FromObject(format);
Fred Drakee4315f52000-05-09 19:53:39 +00009071 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009072 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073 fmt = PyUnicode_AS_UNICODE(uformat);
9074 fmtcnt = PyUnicode_GET_SIZE(uformat);
9075
9076 reslen = rescnt = fmtcnt + 100;
9077 result = _PyUnicode_New(reslen);
9078 if (result == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009079 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009080 res = PyUnicode_AS_UNICODE(result);
9081
9082 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009083 arglen = PyTuple_Size(args);
9084 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009085 }
9086 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009087 arglen = -1;
9088 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009089 }
Christian Heimes90aa7642007-12-19 02:45:37 +00009090 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +00009091 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +00009092 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009093
9094 while (--fmtcnt >= 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009095 if (*fmt != '%') {
9096 if (--rescnt < 0) {
9097 rescnt = fmtcnt + 100;
9098 reslen += rescnt;
9099 if (_PyUnicode_Resize(&result, reslen) < 0)
9100 goto onError;
9101 res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
9102 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009103 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009104 *res++ = *fmt++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009105 }
9106 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 /* Got a format specifier */
9108 int flags = 0;
9109 Py_ssize_t width = -1;
9110 int prec = -1;
9111 Py_UNICODE c = '\0';
9112 Py_UNICODE fill;
9113 int isnumok;
9114 PyObject *v = NULL;
9115 PyObject *temp = NULL;
9116 Py_UNICODE *pbuf;
9117 Py_UNICODE sign;
9118 Py_ssize_t len;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009119 Py_UNICODE formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120
Benjamin Peterson29060642009-01-31 22:14:21 +00009121 fmt++;
9122 if (*fmt == '(') {
9123 Py_UNICODE *keystart;
9124 Py_ssize_t keylen;
9125 PyObject *key;
9126 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +00009127
Benjamin Peterson29060642009-01-31 22:14:21 +00009128 if (dict == NULL) {
9129 PyErr_SetString(PyExc_TypeError,
9130 "format requires a mapping");
9131 goto onError;
9132 }
9133 ++fmt;
9134 --fmtcnt;
9135 keystart = fmt;
9136 /* Skip over balanced parentheses */
9137 while (pcount > 0 && --fmtcnt >= 0) {
9138 if (*fmt == ')')
9139 --pcount;
9140 else if (*fmt == '(')
9141 ++pcount;
9142 fmt++;
9143 }
9144 keylen = fmt - keystart - 1;
9145 if (fmtcnt < 0 || pcount > 0) {
9146 PyErr_SetString(PyExc_ValueError,
9147 "incomplete format key");
9148 goto onError;
9149 }
9150#if 0
9151 /* keys are converted to strings using UTF-8 and
9152 then looked up since Python uses strings to hold
9153 variables names etc. in its namespaces and we
9154 wouldn't want to break common idioms. */
9155 key = PyUnicode_EncodeUTF8(keystart,
9156 keylen,
9157 NULL);
9158#else
9159 key = PyUnicode_FromUnicode(keystart, keylen);
9160#endif
9161 if (key == NULL)
9162 goto onError;
9163 if (args_owned) {
9164 Py_DECREF(args);
9165 args_owned = 0;
9166 }
9167 args = PyObject_GetItem(dict, key);
9168 Py_DECREF(key);
9169 if (args == NULL) {
9170 goto onError;
9171 }
9172 args_owned = 1;
9173 arglen = -1;
9174 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009175 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009176 while (--fmtcnt >= 0) {
9177 switch (c = *fmt++) {
9178 case '-': flags |= F_LJUST; continue;
9179 case '+': flags |= F_SIGN; continue;
9180 case ' ': flags |= F_BLANK; continue;
9181 case '#': flags |= F_ALT; continue;
9182 case '0': flags |= F_ZERO; continue;
9183 }
9184 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009185 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009186 if (c == '*') {
9187 v = getnextarg(args, arglen, &argidx);
9188 if (v == NULL)
9189 goto onError;
9190 if (!PyLong_Check(v)) {
9191 PyErr_SetString(PyExc_TypeError,
9192 "* wants int");
9193 goto onError;
9194 }
9195 width = PyLong_AsLong(v);
9196 if (width == -1 && PyErr_Occurred())
9197 goto onError;
9198 if (width < 0) {
9199 flags |= F_LJUST;
9200 width = -width;
9201 }
9202 if (--fmtcnt >= 0)
9203 c = *fmt++;
9204 }
9205 else if (c >= '0' && c <= '9') {
9206 width = c - '0';
9207 while (--fmtcnt >= 0) {
9208 c = *fmt++;
9209 if (c < '0' || c > '9')
9210 break;
9211 if ((width*10) / 10 != width) {
9212 PyErr_SetString(PyExc_ValueError,
9213 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009214 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009215 }
9216 width = width*10 + (c - '0');
9217 }
9218 }
9219 if (c == '.') {
9220 prec = 0;
9221 if (--fmtcnt >= 0)
9222 c = *fmt++;
9223 if (c == '*') {
9224 v = getnextarg(args, arglen, &argidx);
9225 if (v == NULL)
9226 goto onError;
9227 if (!PyLong_Check(v)) {
9228 PyErr_SetString(PyExc_TypeError,
9229 "* wants int");
9230 goto onError;
9231 }
9232 prec = PyLong_AsLong(v);
9233 if (prec == -1 && PyErr_Occurred())
9234 goto onError;
9235 if (prec < 0)
9236 prec = 0;
9237 if (--fmtcnt >= 0)
9238 c = *fmt++;
9239 }
9240 else if (c >= '0' && c <= '9') {
9241 prec = c - '0';
9242 while (--fmtcnt >= 0) {
Stefan Krah99212f62010-07-19 17:58:26 +00009243 c = *fmt++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009244 if (c < '0' || c > '9')
9245 break;
9246 if ((prec*10) / 10 != prec) {
9247 PyErr_SetString(PyExc_ValueError,
9248 "prec too big");
9249 goto onError;
9250 }
9251 prec = prec*10 + (c - '0');
9252 }
9253 }
9254 } /* prec */
9255 if (fmtcnt >= 0) {
9256 if (c == 'h' || c == 'l' || c == 'L') {
9257 if (--fmtcnt >= 0)
9258 c = *fmt++;
9259 }
9260 }
9261 if (fmtcnt < 0) {
9262 PyErr_SetString(PyExc_ValueError,
9263 "incomplete format");
9264 goto onError;
9265 }
9266 if (c != '%') {
9267 v = getnextarg(args, arglen, &argidx);
9268 if (v == NULL)
9269 goto onError;
9270 }
9271 sign = 0;
9272 fill = ' ';
9273 switch (c) {
9274
9275 case '%':
9276 pbuf = formatbuf;
9277 /* presume that buffer length is at least 1 */
9278 pbuf[0] = '%';
9279 len = 1;
9280 break;
9281
9282 case 's':
9283 case 'r':
9284 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +00009285 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009286 temp = v;
9287 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009288 }
9289 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009290 if (c == 's')
9291 temp = PyObject_Str(v);
9292 else if (c == 'r')
9293 temp = PyObject_Repr(v);
9294 else
9295 temp = PyObject_ASCII(v);
9296 if (temp == NULL)
9297 goto onError;
9298 if (PyUnicode_Check(temp))
9299 /* nothing to do */;
9300 else {
9301 Py_DECREF(temp);
9302 PyErr_SetString(PyExc_TypeError,
9303 "%s argument has non-string str()");
9304 goto onError;
9305 }
9306 }
9307 pbuf = PyUnicode_AS_UNICODE(temp);
9308 len = PyUnicode_GET_SIZE(temp);
9309 if (prec >= 0 && len > prec)
9310 len = prec;
9311 break;
9312
9313 case 'i':
9314 case 'd':
9315 case 'u':
9316 case 'o':
9317 case 'x':
9318 case 'X':
9319 if (c == 'i')
9320 c = 'd';
9321 isnumok = 0;
9322 if (PyNumber_Check(v)) {
9323 PyObject *iobj=NULL;
9324
9325 if (PyLong_Check(v)) {
9326 iobj = v;
9327 Py_INCREF(iobj);
9328 }
9329 else {
9330 iobj = PyNumber_Long(v);
9331 }
9332 if (iobj!=NULL) {
9333 if (PyLong_Check(iobj)) {
9334 isnumok = 1;
9335 temp = formatlong(iobj, flags, prec, c);
9336 Py_DECREF(iobj);
9337 if (!temp)
9338 goto onError;
9339 pbuf = PyUnicode_AS_UNICODE(temp);
9340 len = PyUnicode_GET_SIZE(temp);
9341 sign = 1;
9342 }
9343 else {
9344 Py_DECREF(iobj);
9345 }
9346 }
9347 }
9348 if (!isnumok) {
9349 PyErr_Format(PyExc_TypeError,
9350 "%%%c format: a number is required, "
9351 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
9352 goto onError;
9353 }
9354 if (flags & F_ZERO)
9355 fill = '0';
9356 break;
9357
9358 case 'e':
9359 case 'E':
9360 case 'f':
9361 case 'F':
9362 case 'g':
9363 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009364 temp = formatfloat(v, flags, prec, c);
9365 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +00009366 goto onError;
Mark Dickinsonf489caf2009-05-01 11:42:00 +00009367 pbuf = PyUnicode_AS_UNICODE(temp);
9368 len = PyUnicode_GET_SIZE(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009369 sign = 1;
9370 if (flags & F_ZERO)
9371 fill = '0';
9372 break;
9373
9374 case 'c':
9375 pbuf = formatbuf;
9376 len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
9377 if (len < 0)
9378 goto onError;
9379 break;
9380
9381 default:
9382 PyErr_Format(PyExc_ValueError,
9383 "unsupported format character '%c' (0x%x) "
9384 "at index %zd",
9385 (31<=c && c<=126) ? (char)c : '?',
9386 (int)c,
9387 (Py_ssize_t)(fmt - 1 -
9388 PyUnicode_AS_UNICODE(uformat)));
9389 goto onError;
9390 }
9391 if (sign) {
9392 if (*pbuf == '-' || *pbuf == '+') {
9393 sign = *pbuf++;
9394 len--;
9395 }
9396 else if (flags & F_SIGN)
9397 sign = '+';
9398 else if (flags & F_BLANK)
9399 sign = ' ';
9400 else
9401 sign = 0;
9402 }
9403 if (width < len)
9404 width = len;
9405 if (rescnt - (sign != 0) < width) {
9406 reslen -= rescnt;
9407 rescnt = width + fmtcnt + 100;
9408 reslen += rescnt;
9409 if (reslen < 0) {
9410 Py_XDECREF(temp);
9411 PyErr_NoMemory();
9412 goto onError;
9413 }
9414 if (_PyUnicode_Resize(&result, reslen) < 0) {
9415 Py_XDECREF(temp);
9416 goto onError;
9417 }
9418 res = PyUnicode_AS_UNICODE(result)
9419 + reslen - rescnt;
9420 }
9421 if (sign) {
9422 if (fill != ' ')
9423 *res++ = sign;
9424 rescnt--;
9425 if (width > len)
9426 width--;
9427 }
9428 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9429 assert(pbuf[0] == '0');
9430 assert(pbuf[1] == c);
9431 if (fill != ' ') {
9432 *res++ = *pbuf++;
9433 *res++ = *pbuf++;
9434 }
9435 rescnt -= 2;
9436 width -= 2;
9437 if (width < 0)
9438 width = 0;
9439 len -= 2;
9440 }
9441 if (width > len && !(flags & F_LJUST)) {
9442 do {
9443 --rescnt;
9444 *res++ = fill;
9445 } while (--width > len);
9446 }
9447 if (fill == ' ') {
9448 if (sign)
9449 *res++ = sign;
9450 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
9451 assert(pbuf[0] == '0');
9452 assert(pbuf[1] == c);
9453 *res++ = *pbuf++;
9454 *res++ = *pbuf++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009455 }
9456 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009457 Py_UNICODE_COPY(res, pbuf, len);
9458 res += len;
9459 rescnt -= len;
9460 while (--width >= len) {
9461 --rescnt;
9462 *res++ = ' ';
9463 }
9464 if (dict && (argidx < arglen) && c != '%') {
9465 PyErr_SetString(PyExc_TypeError,
9466 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +00009467 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +00009468 goto onError;
9469 }
9470 Py_XDECREF(temp);
9471 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472 } /* until end */
9473 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 PyErr_SetString(PyExc_TypeError,
9475 "not all arguments converted during string formatting");
9476 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477 }
9478
Thomas Woutersa96affe2006-03-12 00:29:36 +00009479 if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009482 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 }
9484 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485 return (PyObject *)result;
9486
Benjamin Peterson29060642009-01-31 22:14:21 +00009487 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488 Py_XDECREF(result);
9489 Py_DECREF(uformat);
9490 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009491 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492 }
9493 return NULL;
9494}
9495
Jeremy Hylton938ace62002-07-17 16:30:39 +00009496static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +00009497unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
9498
Tim Peters6d6c1a32001-08-02 04:15:00 +00009499static PyObject *
9500unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9501{
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009503 static char *kwlist[] = {"object", "encoding", "errors", 0};
9504 char *encoding = NULL;
9505 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00009506
Benjamin Peterson14339b62009-01-31 16:36:08 +00009507 if (type != &PyUnicode_Type)
9508 return unicode_subtype_new(type, args, kwds);
9509 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +00009510 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009511 return NULL;
9512 if (x == NULL)
9513 return (PyObject *)_PyUnicode_New(0);
9514 if (encoding == NULL && errors == NULL)
9515 return PyObject_Str(x);
9516 else
Benjamin Peterson29060642009-01-31 22:14:21 +00009517 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +00009518}
9519
Guido van Rossume023fe02001-08-30 03:12:59 +00009520static PyObject *
9521unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
9522{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009523 PyUnicodeObject *tmp, *pnew;
9524 Py_ssize_t n;
Guido van Rossume023fe02001-08-30 03:12:59 +00009525
Benjamin Peterson14339b62009-01-31 16:36:08 +00009526 assert(PyType_IsSubtype(type, &PyUnicode_Type));
9527 tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
9528 if (tmp == NULL)
9529 return NULL;
9530 assert(PyUnicode_Check(tmp));
9531 pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
9532 if (pnew == NULL) {
9533 Py_DECREF(tmp);
9534 return NULL;
9535 }
9536 pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
9537 if (pnew->str == NULL) {
9538 _Py_ForgetReference((PyObject *)pnew);
9539 PyObject_Del(pnew);
9540 Py_DECREF(tmp);
9541 return PyErr_NoMemory();
9542 }
9543 Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
9544 pnew->length = n;
9545 pnew->hash = tmp->hash;
9546 Py_DECREF(tmp);
9547 return (PyObject *)pnew;
Guido van Rossume023fe02001-08-30 03:12:59 +00009548}
9549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009550PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009551 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00009552\n\
Collin Winterd474ce82007-08-07 19:42:11 +00009553Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +00009554encoding defaults to the current default string encoding.\n\
9555errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00009556
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009557static PyObject *unicode_iter(PyObject *seq);
9558
Guido van Rossumd57fd912000-03-10 22:53:23 +00009559PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00009560 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +00009561 "str", /* tp_name */
9562 sizeof(PyUnicodeObject), /* tp_size */
9563 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009565 (destructor)unicode_dealloc, /* tp_dealloc */
9566 0, /* tp_print */
9567 0, /* tp_getattr */
9568 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009569 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009570 unicode_repr, /* tp_repr */
9571 &unicode_as_number, /* tp_as_number */
9572 &unicode_as_sequence, /* tp_as_sequence */
9573 &unicode_as_mapping, /* tp_as_mapping */
9574 (hashfunc) unicode_hash, /* tp_hash*/
9575 0, /* tp_call*/
9576 (reprfunc) unicode_str, /* tp_str */
9577 PyObject_GenericGetAttr, /* tp_getattro */
9578 0, /* tp_setattro */
9579 0, /* tp_as_buffer */
9580 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +00009581 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009582 unicode_doc, /* tp_doc */
9583 0, /* tp_traverse */
9584 0, /* tp_clear */
9585 PyUnicode_RichCompare, /* tp_richcompare */
9586 0, /* tp_weaklistoffset */
9587 unicode_iter, /* tp_iter */
9588 0, /* tp_iternext */
9589 unicode_methods, /* tp_methods */
9590 0, /* tp_members */
9591 0, /* tp_getset */
9592 &PyBaseObject_Type, /* tp_base */
9593 0, /* tp_dict */
9594 0, /* tp_descr_get */
9595 0, /* tp_descr_set */
9596 0, /* tp_dictoffset */
9597 0, /* tp_init */
9598 0, /* tp_alloc */
9599 unicode_new, /* tp_new */
9600 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601};
9602
9603/* Initialize the Unicode implementation */
9604
Thomas Wouters78890102000-07-22 19:25:51 +00009605void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009607 int i;
9608
Thomas Wouters477c8d52006-05-27 19:21:47 +00009609 /* XXX - move this array to unicodectype.c ? */
9610 Py_UNICODE linebreak[] = {
9611 0x000A, /* LINE FEED */
9612 0x000D, /* CARRIAGE RETURN */
9613 0x001C, /* FILE SEPARATOR */
9614 0x001D, /* GROUP SEPARATOR */
9615 0x001E, /* RECORD SEPARATOR */
9616 0x0085, /* NEXT LINE */
9617 0x2028, /* LINE SEPARATOR */
9618 0x2029, /* PARAGRAPH SEPARATOR */
9619 };
9620
Fred Drakee4315f52000-05-09 19:53:39 +00009621 /* Init the implementation */
Christian Heimes2202f872008-02-06 14:31:34 +00009622 free_list = NULL;
9623 numfree = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624 unicode_empty = _PyUnicode_New(0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009625 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00009626 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009627
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009628 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00009629 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +00009630 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009631 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +00009632
9633 /* initialize the linebreak bloom filter */
9634 bloom_linebreak = make_bloom_mask(
9635 linebreak, sizeof(linebreak) / sizeof(linebreak[0])
9636 );
Thomas Wouters0e3f5912006-08-11 14:57:12 +00009637
9638 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639}
9640
9641/* Finalize the Unicode implementation */
9642
Christian Heimesa156e092008-02-16 07:38:31 +00009643int
9644PyUnicode_ClearFreeList(void)
9645{
9646 int freelist_size = numfree;
9647 PyUnicodeObject *u;
9648
9649 for (u = free_list; u != NULL;) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009650 PyUnicodeObject *v = u;
9651 u = *(PyUnicodeObject **)u;
9652 if (v->str)
9653 PyObject_DEL(v->str);
9654 Py_XDECREF(v->defenc);
9655 PyObject_Del(v);
9656 numfree--;
Christian Heimesa156e092008-02-16 07:38:31 +00009657 }
9658 free_list = NULL;
9659 assert(numfree == 0);
9660 return freelist_size;
9661}
9662
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663void
Thomas Wouters78890102000-07-22 19:25:51 +00009664_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009665{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009666 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009667
Guido van Rossum4ae8ef82000-10-03 18:09:04 +00009668 Py_XDECREF(unicode_empty);
9669 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +00009670
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009671 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009672 if (unicode_latin1[i]) {
9673 Py_DECREF(unicode_latin1[i]);
9674 unicode_latin1[i] = NULL;
9675 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009676 }
Christian Heimesa156e092008-02-16 07:38:31 +00009677 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00009679
Walter Dörwald16807132007-05-25 13:52:07 +00009680void
9681PyUnicode_InternInPlace(PyObject **p)
9682{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009683 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
9684 PyObject *t;
9685 if (s == NULL || !PyUnicode_Check(s))
9686 Py_FatalError(
9687 "PyUnicode_InternInPlace: unicode strings only please!");
9688 /* If it's a subclass, we don't really know what putting
9689 it in the interned dict might do. */
9690 if (!PyUnicode_CheckExact(s))
9691 return;
9692 if (PyUnicode_CHECK_INTERNED(s))
9693 return;
9694 if (interned == NULL) {
9695 interned = PyDict_New();
9696 if (interned == NULL) {
9697 PyErr_Clear(); /* Don't leave an exception */
9698 return;
9699 }
9700 }
9701 /* It might be that the GetItem call fails even
9702 though the key is present in the dictionary,
9703 namely when this happens during a stack overflow. */
9704 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +00009705 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009706 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +00009707
Benjamin Peterson29060642009-01-31 22:14:21 +00009708 if (t) {
9709 Py_INCREF(t);
9710 Py_DECREF(*p);
9711 *p = t;
9712 return;
9713 }
Walter Dörwald16807132007-05-25 13:52:07 +00009714
Benjamin Peterson14339b62009-01-31 16:36:08 +00009715 PyThreadState_GET()->recursion_critical = 1;
9716 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
9717 PyErr_Clear();
9718 PyThreadState_GET()->recursion_critical = 0;
9719 return;
9720 }
9721 PyThreadState_GET()->recursion_critical = 0;
9722 /* The two references in interned are not counted by refcnt.
9723 The deallocator will take care of this */
9724 Py_REFCNT(s) -= 2;
9725 PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +00009726}
9727
9728void
9729PyUnicode_InternImmortal(PyObject **p)
9730{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009731 PyUnicode_InternInPlace(p);
9732 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
9733 PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
9734 Py_INCREF(*p);
9735 }
Walter Dörwald16807132007-05-25 13:52:07 +00009736}
9737
9738PyObject *
9739PyUnicode_InternFromString(const char *cp)
9740{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009741 PyObject *s = PyUnicode_FromString(cp);
9742 if (s == NULL)
9743 return NULL;
9744 PyUnicode_InternInPlace(&s);
9745 return s;
Walter Dörwald16807132007-05-25 13:52:07 +00009746}
9747
9748void _Py_ReleaseInternedUnicodeStrings(void)
9749{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009750 PyObject *keys;
9751 PyUnicodeObject *s;
9752 Py_ssize_t i, n;
9753 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +00009754
Benjamin Peterson14339b62009-01-31 16:36:08 +00009755 if (interned == NULL || !PyDict_Check(interned))
9756 return;
9757 keys = PyDict_Keys(interned);
9758 if (keys == NULL || !PyList_Check(keys)) {
9759 PyErr_Clear();
9760 return;
9761 }
Walter Dörwald16807132007-05-25 13:52:07 +00009762
Benjamin Peterson14339b62009-01-31 16:36:08 +00009763 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
9764 detector, interned unicode strings are not forcibly deallocated;
9765 rather, we give them their stolen references back, and then clear
9766 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +00009767
Benjamin Peterson14339b62009-01-31 16:36:08 +00009768 n = PyList_GET_SIZE(keys);
9769 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +00009770 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009771 for (i = 0; i < n; i++) {
9772 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
9773 switch (s->state) {
9774 case SSTATE_NOT_INTERNED:
9775 /* XXX Shouldn't happen */
9776 break;
9777 case SSTATE_INTERNED_IMMORTAL:
9778 Py_REFCNT(s) += 1;
9779 immortal_size += s->length;
9780 break;
9781 case SSTATE_INTERNED_MORTAL:
9782 Py_REFCNT(s) += 2;
9783 mortal_size += s->length;
9784 break;
9785 default:
9786 Py_FatalError("Inconsistent interned string state.");
9787 }
9788 s->state = SSTATE_NOT_INTERNED;
9789 }
9790 fprintf(stderr, "total size of all interned strings: "
9791 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
9792 "mortal/immortal\n", mortal_size, immortal_size);
9793 Py_DECREF(keys);
9794 PyDict_Clear(interned);
9795 Py_DECREF(interned);
9796 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +00009797}
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009798
9799
9800/********************* Unicode Iterator **************************/
9801
9802typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009803 PyObject_HEAD
9804 Py_ssize_t it_index;
9805 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009806} unicodeiterobject;
9807
9808static void
9809unicodeiter_dealloc(unicodeiterobject *it)
9810{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009811 _PyObject_GC_UNTRACK(it);
9812 Py_XDECREF(it->it_seq);
9813 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009814}
9815
9816static int
9817unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
9818{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009819 Py_VISIT(it->it_seq);
9820 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009821}
9822
9823static PyObject *
9824unicodeiter_next(unicodeiterobject *it)
9825{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009826 PyUnicodeObject *seq;
9827 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009828
Benjamin Peterson14339b62009-01-31 16:36:08 +00009829 assert(it != NULL);
9830 seq = it->it_seq;
9831 if (seq == NULL)
9832 return NULL;
9833 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009834
Benjamin Peterson14339b62009-01-31 16:36:08 +00009835 if (it->it_index < PyUnicode_GET_SIZE(seq)) {
9836 item = PyUnicode_FromUnicode(
Benjamin Peterson29060642009-01-31 22:14:21 +00009837 PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009838 if (item != NULL)
9839 ++it->it_index;
9840 return item;
9841 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009842
Benjamin Peterson14339b62009-01-31 16:36:08 +00009843 Py_DECREF(seq);
9844 it->it_seq = NULL;
9845 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009846}
9847
9848static PyObject *
9849unicodeiter_len(unicodeiterobject *it)
9850{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009851 Py_ssize_t len = 0;
9852 if (it->it_seq)
9853 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
9854 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009855}
9856
9857PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
9858
9859static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009860 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00009861 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +00009862 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009863};
9864
9865PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009866 PyVarObject_HEAD_INIT(&PyType_Type, 0)
9867 "str_iterator", /* tp_name */
9868 sizeof(unicodeiterobject), /* tp_basicsize */
9869 0, /* tp_itemsize */
9870 /* methods */
9871 (destructor)unicodeiter_dealloc, /* tp_dealloc */
9872 0, /* tp_print */
9873 0, /* tp_getattr */
9874 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00009875 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +00009876 0, /* tp_repr */
9877 0, /* tp_as_number */
9878 0, /* tp_as_sequence */
9879 0, /* tp_as_mapping */
9880 0, /* tp_hash */
9881 0, /* tp_call */
9882 0, /* tp_str */
9883 PyObject_GenericGetAttr, /* tp_getattro */
9884 0, /* tp_setattro */
9885 0, /* tp_as_buffer */
9886 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
9887 0, /* tp_doc */
9888 (traverseproc)unicodeiter_traverse, /* tp_traverse */
9889 0, /* tp_clear */
9890 0, /* tp_richcompare */
9891 0, /* tp_weaklistoffset */
9892 PyObject_SelfIter, /* tp_iter */
9893 (iternextfunc)unicodeiter_next, /* tp_iternext */
9894 unicodeiter_methods, /* tp_methods */
9895 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009896};
9897
9898static PyObject *
9899unicode_iter(PyObject *seq)
9900{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009901 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009902
Benjamin Peterson14339b62009-01-31 16:36:08 +00009903 if (!PyUnicode_Check(seq)) {
9904 PyErr_BadInternalCall();
9905 return NULL;
9906 }
9907 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
9908 if (it == NULL)
9909 return NULL;
9910 it->it_index = 0;
9911 Py_INCREF(seq);
9912 it->it_seq = (PyUnicodeObject *)seq;
9913 _PyObject_GC_TRACK(it);
9914 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00009915}
9916
Martin v. Löwis5b222132007-06-10 09:51:05 +00009917size_t
9918Py_UNICODE_strlen(const Py_UNICODE *u)
9919{
9920 int res = 0;
9921 while(*u++)
9922 res++;
9923 return res;
9924}
9925
9926Py_UNICODE*
9927Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
9928{
9929 Py_UNICODE *u = s1;
9930 while ((*u++ = *s2++));
9931 return s1;
9932}
9933
9934Py_UNICODE*
9935Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
9936{
9937 Py_UNICODE *u = s1;
9938 while ((*u++ = *s2++))
9939 if (n-- == 0)
9940 break;
9941 return s1;
9942}
9943
9944int
9945Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
9946{
9947 while (*s1 && *s2 && *s1 == *s2)
9948 s1++, s2++;
9949 if (*s1 && *s2)
9950 return (*s1 < *s2) ? -1 : +1;
9951 if (*s1)
9952 return 1;
9953 if (*s2)
9954 return -1;
9955 return 0;
9956}
9957
9958Py_UNICODE*
9959Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
9960{
9961 const Py_UNICODE *p;
9962 for (p = s; *p; p++)
9963 if (*p == c)
9964 return (Py_UNICODE*)p;
9965 return NULL;
9966}
9967
9968
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009969#ifdef __cplusplus
9970}
9971#endif