blob: 1aabd2e5dd4052e36e16e47a76640ff818072239 [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,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Guido van Rossumd57fd912000-03-10 22:53:23 +000049/* Limit for the Unicode object free list */
50
Christian Heimes2202f872008-02-06 14:31:34 +000051#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000052
53/* Limit for the Unicode object free list stay alive optimization.
54
55 The implementation will keep allocated Unicode memory intact for
56 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000057 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000058
Christian Heimes2202f872008-02-06 14:31:34 +000059 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000060 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000061 malloc()-overhead) bytes of unused garbage.
62
63 Setting the limit to 0 effectively turns the feature off.
64
Guido van Rossumfd4b9572000-04-10 13:51:10 +000065 Note: This is an experimental feature ! If you get core dumps when
66 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
68*/
69
Guido van Rossumfd4b9572000-04-10 13:51:10 +000070#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000071
72/* Endianness switches; defaults to little endian */
73
74#ifdef WORDS_BIGENDIAN
75# define BYTEORDER_IS_BIG_ENDIAN
76#else
77# define BYTEORDER_IS_LITTLE_ENDIAN
78#endif
79
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000080/* --- Globals ------------------------------------------------------------
81
82 The globals are initialized by the _PyUnicode_Init() API and should
83 not be used before calling that API.
84
85*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000086
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087
88#ifdef __cplusplus
89extern "C" {
90#endif
91
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020092/* Generic helper macro to convert characters of different types.
93 from_type and to_type have to be valid type names, begin and end
94 are pointers to the source characters which should be of type
95 "from_type *". to is a pointer of type "to_type *" and points to the
96 buffer where the result characters are written to. */
97#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
98 do { \
99 const from_type *iter_; to_type *to_; \
100 for (iter_ = (begin), to_ = (to_type *)(to); \
101 iter_ < (end); \
102 ++iter_, ++to_) { \
103 *to_ = (to_type)*iter_; \
104 } \
105 } while (0)
106
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200107#define _PyUnicode_UTF8(op) \
108 (((PyCompactUnicodeObject*)(op))->utf8)
109#define PyUnicode_UTF8(op) \
110 (assert(PyUnicode_Check(op)), \
111 assert(PyUnicode_IS_READY(op)), \
112 PyUnicode_IS_COMPACT_ASCII(op) ? \
113 ((char*)((PyASCIIObject*)(op) + 1)) : \
114 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200115#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200116 (((PyCompactUnicodeObject*)(op))->utf8_length)
117#define PyUnicode_UTF8_LENGTH(op) \
118 (assert(PyUnicode_Check(op)), \
119 assert(PyUnicode_IS_READY(op)), \
120 PyUnicode_IS_COMPACT_ASCII(op) ? \
121 ((PyASCIIObject*)(op))->length : \
122 _PyUnicode_UTF8_LENGTH(op))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200123#define _PyUnicode_WSTR(op) (((PyASCIIObject*)(op))->wstr)
124#define _PyUnicode_WSTR_LENGTH(op) (((PyCompactUnicodeObject*)(op))->wstr_length)
125#define _PyUnicode_LENGTH(op) (((PyASCIIObject *)(op))->length)
126#define _PyUnicode_STATE(op) (((PyASCIIObject *)(op))->state)
127#define _PyUnicode_HASH(op) (((PyASCIIObject *)(op))->hash)
128#define _PyUnicode_KIND(op) \
129 (assert(PyUnicode_Check(op)), \
130 ((PyASCIIObject *)(op))->state.kind)
131#define _PyUnicode_GET_LENGTH(op) \
132 (assert(PyUnicode_Check(op)), \
133 ((PyASCIIObject *)(op))->length)
Victor Stinnerc3c74152011-10-02 20:39:55 +0200134#define _PyUnicode_DATA_ANY(op) (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200135
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200136/* The Unicode string has been modified: reset the hash */
137#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
138
Walter Dörwald16807132007-05-25 13:52:07 +0000139/* This dictionary holds all interned unicode strings. Note that references
140 to strings in this dictionary are *not* counted in the string's ob_refcnt.
141 When the interned string reaches a refcnt of 0 the string deallocation
142 function will delete the reference from this dictionary.
143
144 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000145 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000146*/
147static PyObject *interned;
148
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000149/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200150static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000151
152/* Single character Unicode strings in the Latin-1 range are being
153 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200154static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000155
Christian Heimes190d79e2008-01-30 11:58:22 +0000156/* Fast detection of the most frequent whitespace characters */
157const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000158 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000159/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000160/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000161/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000162/* case 0x000C: * FORM FEED */
163/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000164 0, 1, 1, 1, 1, 1, 0, 0,
165 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000166/* case 0x001C: * FILE SEPARATOR */
167/* case 0x001D: * GROUP SEPARATOR */
168/* case 0x001E: * RECORD SEPARATOR */
169/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000170 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000171/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000172 1, 0, 0, 0, 0, 0, 0, 0,
173 0, 0, 0, 0, 0, 0, 0, 0,
174 0, 0, 0, 0, 0, 0, 0, 0,
175 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000176
Benjamin Peterson14339b62009-01-31 16:36:08 +0000177 0, 0, 0, 0, 0, 0, 0, 0,
178 0, 0, 0, 0, 0, 0, 0, 0,
179 0, 0, 0, 0, 0, 0, 0, 0,
180 0, 0, 0, 0, 0, 0, 0, 0,
181 0, 0, 0, 0, 0, 0, 0, 0,
182 0, 0, 0, 0, 0, 0, 0, 0,
183 0, 0, 0, 0, 0, 0, 0, 0,
184 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000185};
186
Alexander Belopolsky40018472011-02-26 01:02:56 +0000187static PyObject *
188unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000189 PyObject **errorHandler,const char *encoding, const char *reason,
190 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
191 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
192
Alexander Belopolsky40018472011-02-26 01:02:56 +0000193static void
194raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300195 const char *encoding,
196 const Py_UNICODE *unicode, Py_ssize_t size,
197 Py_ssize_t startpos, Py_ssize_t endpos,
198 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000199
Christian Heimes190d79e2008-01-30 11:58:22 +0000200/* Same for linebreaks */
201static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000202 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000204/* 0x000B, * LINE TABULATION */
205/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000206/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000207 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000209/* 0x001C, * FILE SEPARATOR */
210/* 0x001D, * GROUP SEPARATOR */
211/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000212 0, 0, 0, 0, 1, 1, 1, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300228/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
229 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000230Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000231PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000232{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000233#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000235#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000236 /* This is actually an illegal character, so it should
237 not be passed to unichr. */
238 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000239#endif
240}
241
Thomas Wouters477c8d52006-05-27 19:21:47 +0000242/* --- Bloom Filters ----------------------------------------------------- */
243
244/* stuff to implement simple "bloom filters" for Unicode characters.
245 to keep things simple, we use a single bitmask, using the least 5
246 bits from each unicode characters as the bit index. */
247
248/* the linebreak mask is set up by Unicode_Init below */
249
Antoine Pitrouf068f942010-01-13 14:19:12 +0000250#if LONG_BIT >= 128
251#define BLOOM_WIDTH 128
252#elif LONG_BIT >= 64
253#define BLOOM_WIDTH 64
254#elif LONG_BIT >= 32
255#define BLOOM_WIDTH 32
256#else
257#error "LONG_BIT is smaller than 32"
258#endif
259
Thomas Wouters477c8d52006-05-27 19:21:47 +0000260#define BLOOM_MASK unsigned long
261
262static BLOOM_MASK bloom_linebreak;
263
Antoine Pitrouf068f942010-01-13 14:19:12 +0000264#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
265#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000266
Benjamin Peterson29060642009-01-31 22:14:21 +0000267#define BLOOM_LINEBREAK(ch) \
268 ((ch) < 128U ? ascii_linebreak[(ch)] : \
269 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000270
Alexander Belopolsky40018472011-02-26 01:02:56 +0000271Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200272make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273{
274 /* calculate simple bloom-style bitmask for a given unicode string */
275
Antoine Pitrouf068f942010-01-13 14:19:12 +0000276 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000277 Py_ssize_t i;
278
279 mask = 0;
280 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000282
283 return mask;
284}
285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200286#define BLOOM_MEMBER(mask, chr, str) \
287 (BLOOM(mask, chr) \
288 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000289
Guido van Rossumd57fd912000-03-10 22:53:23 +0000290/* --- Unicode Object ----------------------------------------------------- */
291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200293fixup(PyUnicodeObject *self, Py_UCS4 (*fixfct)(PyUnicodeObject *s));
294
295Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
296 Py_ssize_t size, Py_UCS4 ch,
297 int direction)
298{
299 /* like wcschr, but doesn't stop at NULL characters */
300 Py_ssize_t i;
301 if (direction == 1) {
302 for(i = 0; i < size; i++)
303 if (PyUnicode_READ(kind, s, i) == ch)
304 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
305 }
306 else {
307 for(i = size-1; i >= 0; i--)
308 if (PyUnicode_READ(kind, s, i) == ch)
309 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
310 }
311 return NULL;
312}
313
Alexander Belopolsky40018472011-02-26 01:02:56 +0000314static int
315unicode_resize(register PyUnicodeObject *unicode,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200316 Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000317{
318 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200320 /* Resizing is only supported for old unicode objects. */
321 assert(!PyUnicode_IS_COMPACT(unicode));
322 assert(_PyUnicode_WSTR(unicode) != NULL);
323
324 /* ... and only if they have not been readied yet, because
325 callees usually rely on the wstr representation when resizing. */
326 assert(unicode->data.any == NULL);
327
Guido van Rossumfd4b9572000-04-10 13:51:10 +0000328 /* Shortcut if there's nothing much to do. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200329 if (_PyUnicode_WSTR_LENGTH(unicode) == length)
Benjamin Peterson29060642009-01-31 22:14:21 +0000330 goto reset;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000331
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000332 /* Resizing shared object (unicode_empty or single character
333 objects) in-place is not allowed. Use PyUnicode_Resize()
334 instead ! */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000335
Benjamin Peterson14339b62009-01-31 16:36:08 +0000336 if (unicode == unicode_empty ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200337 (_PyUnicode_WSTR_LENGTH(unicode) == 1 &&
338 _PyUnicode_WSTR(unicode)[0] < 256U &&
339 unicode_latin1[_PyUnicode_WSTR(unicode)[0]] == unicode)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +0000340 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson142957c2008-07-04 19:55:29 +0000341 "can't resize shared str objects");
Guido van Rossumd57fd912000-03-10 22:53:23 +0000342 return -1;
343 }
344
Thomas Wouters477c8d52006-05-27 19:21:47 +0000345 /* We allocate one more byte to make sure the string is Ux0000 terminated.
346 The overallocation is also used by fastsearch, which assumes that it's
347 safe to look at str[length] (without making any assumptions about what
348 it contains). */
349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200350 oldstr = _PyUnicode_WSTR(unicode);
351 _PyUnicode_WSTR(unicode) = PyObject_REALLOC(_PyUnicode_WSTR(unicode),
352 sizeof(Py_UNICODE) * (length + 1));
353 if (!_PyUnicode_WSTR(unicode)) {
354 _PyUnicode_WSTR(unicode) = (Py_UNICODE *)oldstr;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000355 PyErr_NoMemory();
356 return -1;
357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200358 _PyUnicode_WSTR(unicode)[length] = 0;
359 _PyUnicode_WSTR_LENGTH(unicode) = length;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000360
Benjamin Peterson29060642009-01-31 22:14:21 +0000361 reset:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200362 if (unicode->data.any != NULL) {
363 PyObject_FREE(unicode->data.any);
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200364 if (_PyUnicode_UTF8(unicode) && _PyUnicode_UTF8(unicode) != unicode->data.any) {
365 PyObject_FREE(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200366 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200367 _PyUnicode_UTF8(unicode) = NULL;
368 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200369 unicode->data.any = NULL;
370 _PyUnicode_LENGTH(unicode) = 0;
371 _PyUnicode_STATE(unicode).interned = _PyUnicode_STATE(unicode).interned;
372 _PyUnicode_STATE(unicode).kind = PyUnicode_WCHAR_KIND;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000373 }
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200374 _PyUnicode_DIRTY(unicode);
Tim Petersced69f82003-09-16 20:30:58 +0000375
Guido van Rossumd57fd912000-03-10 22:53:23 +0000376 return 0;
377}
378
379/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000380 Ux0000 terminated; some code (e.g. new_identifier)
381 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000382
383 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000384 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000385
386*/
387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200388#ifdef Py_DEBUG
389int unicode_old_new_calls = 0;
390#endif
391
Alexander Belopolsky40018472011-02-26 01:02:56 +0000392static PyUnicodeObject *
393_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000394{
395 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200396 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000397
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000399 if (length == 0 && unicode_empty != NULL) {
400 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200401 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000402 }
403
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000404 /* Ensure we won't overflow the size. */
405 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
406 return (PyUnicodeObject *)PyErr_NoMemory();
407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200408 if (length < 0) {
409 PyErr_SetString(PyExc_SystemError,
410 "Negative size passed to _PyUnicode_New");
411 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000412 }
413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200414#ifdef Py_DEBUG
415 ++unicode_old_new_calls;
416#endif
417
418 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
419 if (unicode == NULL)
420 return NULL;
421 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
422 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
423 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000424 PyErr_NoMemory();
425 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200427
Jeremy Hyltond8082792003-09-16 19:41:39 +0000428 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000429 * the caller fails before initializing str -- unicode_resize()
430 * reads str[0], and the Keep-Alive optimization can keep memory
431 * allocated for str alive across a call to unicode_dealloc(unicode).
432 * We don't want unicode_resize to read uninitialized memory in
433 * that case.
434 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200435 _PyUnicode_WSTR(unicode)[0] = 0;
436 _PyUnicode_WSTR(unicode)[length] = 0;
437 _PyUnicode_WSTR_LENGTH(unicode) = length;
438 _PyUnicode_HASH(unicode) = -1;
439 _PyUnicode_STATE(unicode).interned = 0;
440 _PyUnicode_STATE(unicode).kind = 0;
441 _PyUnicode_STATE(unicode).compact = 0;
442 _PyUnicode_STATE(unicode).ready = 0;
443 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200444 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200446 _PyUnicode_UTF8(unicode) = NULL;
447 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000448 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000449
Benjamin Peterson29060642009-01-31 22:14:21 +0000450 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000451 /* XXX UNREF/NEWREF interface should be more symmetrical */
452 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000453 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000454 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000455 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000456}
457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200458#ifdef Py_DEBUG
459int unicode_new_new_calls = 0;
460
461/* Functions wrapping macros for use in debugger */
462char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200463 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200464}
465
466void *_PyUnicode_compact_data(void *unicode) {
467 return _PyUnicode_COMPACT_DATA(unicode);
468}
469void *_PyUnicode_data(void *unicode){
470 printf("obj %p\n", unicode);
471 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
472 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
473 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
474 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
475 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
476 return PyUnicode_DATA(unicode);
477}
478#endif
479
480PyObject *
481PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
482{
483 PyObject *obj;
484 PyCompactUnicodeObject *unicode;
485 void *data;
486 int kind_state;
487 int is_sharing = 0, is_ascii = 0;
488 Py_ssize_t char_size;
489 Py_ssize_t struct_size;
490
491 /* Optimization for empty strings */
492 if (size == 0 && unicode_empty != NULL) {
493 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200494 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200495 }
496
497#ifdef Py_DEBUG
498 ++unicode_new_new_calls;
499#endif
500
501 struct_size = sizeof(PyCompactUnicodeObject);
502 if (maxchar < 128) {
503 kind_state = PyUnicode_1BYTE_KIND;
504 char_size = 1;
505 is_ascii = 1;
506 struct_size = sizeof(PyASCIIObject);
507 }
508 else if (maxchar < 256) {
509 kind_state = PyUnicode_1BYTE_KIND;
510 char_size = 1;
511 }
512 else if (maxchar < 65536) {
513 kind_state = PyUnicode_2BYTE_KIND;
514 char_size = 2;
515 if (sizeof(wchar_t) == 2)
516 is_sharing = 1;
517 }
518 else {
519 kind_state = PyUnicode_4BYTE_KIND;
520 char_size = 4;
521 if (sizeof(wchar_t) == 4)
522 is_sharing = 1;
523 }
524
525 /* Ensure we won't overflow the size. */
526 if (size < 0) {
527 PyErr_SetString(PyExc_SystemError,
528 "Negative size passed to PyUnicode_New");
529 return NULL;
530 }
531 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
532 return PyErr_NoMemory();
533
534 /* Duplicated allocation code from _PyObject_New() instead of a call to
535 * PyObject_New() so we are able to allocate space for the object and
536 * it's data buffer.
537 */
538 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
539 if (obj == NULL)
540 return PyErr_NoMemory();
541 obj = PyObject_INIT(obj, &PyUnicode_Type);
542 if (obj == NULL)
543 return NULL;
544
545 unicode = (PyCompactUnicodeObject *)obj;
546 if (is_ascii)
547 data = ((PyASCIIObject*)obj) + 1;
548 else
549 data = unicode + 1;
550 _PyUnicode_LENGTH(unicode) = size;
551 _PyUnicode_HASH(unicode) = -1;
552 _PyUnicode_STATE(unicode).interned = 0;
553 _PyUnicode_STATE(unicode).kind = kind_state;
554 _PyUnicode_STATE(unicode).compact = 1;
555 _PyUnicode_STATE(unicode).ready = 1;
556 _PyUnicode_STATE(unicode).ascii = is_ascii;
557 if (is_ascii) {
558 ((char*)data)[size] = 0;
559 _PyUnicode_WSTR(unicode) = NULL;
560 }
561 else if (kind_state == PyUnicode_1BYTE_KIND) {
562 ((char*)data)[size] = 0;
563 _PyUnicode_WSTR(unicode) = NULL;
564 _PyUnicode_WSTR_LENGTH(unicode) = 0;
565 unicode->utf8_length = 0;
566 unicode->utf8 = NULL;
567 }
568 else {
569 unicode->utf8 = NULL;
570 if (kind_state == PyUnicode_2BYTE_KIND)
571 ((Py_UCS2*)data)[size] = 0;
572 else /* kind_state == PyUnicode_4BYTE_KIND */
573 ((Py_UCS4*)data)[size] = 0;
574 if (is_sharing) {
575 _PyUnicode_WSTR_LENGTH(unicode) = size;
576 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
577 }
578 else {
579 _PyUnicode_WSTR_LENGTH(unicode) = 0;
580 _PyUnicode_WSTR(unicode) = NULL;
581 }
582 }
583 return obj;
584}
585
586#if SIZEOF_WCHAR_T == 2
587/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
588 will decode surrogate pairs, the other conversions are implemented as macros
589 for efficency.
590
591 This function assumes that unicode can hold one more code point than wstr
592 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200593static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200594unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
595 PyUnicodeObject *unicode)
596{
597 const wchar_t *iter;
598 Py_UCS4 *ucs4_out;
599
600 assert(unicode && PyUnicode_Check(unicode));
601 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
602 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
603
604 for (iter = begin; iter < end; ) {
605 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
606 _PyUnicode_GET_LENGTH(unicode)));
607 if (*iter >= 0xD800 && *iter <= 0xDBFF
608 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
609 {
610 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
611 iter += 2;
612 }
613 else {
614 *ucs4_out++ = *iter;
615 iter++;
616 }
617 }
618 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
619 _PyUnicode_GET_LENGTH(unicode)));
620
621 return 0;
622}
623#endif
624
Victor Stinnercd9950f2011-10-02 00:34:53 +0200625static int
626_PyUnicode_Dirty(PyObject *unicode)
627{
628 assert(PyUnicode_Check(unicode));
629 if (Py_REFCNT(unicode) != 1) {
630 PyErr_SetString(PyExc_ValueError,
631 "Cannot modify a string having more than 1 reference");
632 return -1;
633 }
634 _PyUnicode_DIRTY(unicode);
635 return 0;
636}
637
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200638Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200639PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
640 PyObject *from, Py_ssize_t from_start,
641 Py_ssize_t how_many)
642{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200643 unsigned int from_kind, to_kind;
644 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645
Victor Stinnerb1536152011-09-30 02:26:10 +0200646 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
647 PyErr_BadInternalCall();
648 return -1;
649 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200650
651 if (PyUnicode_READY(from))
652 return -1;
653 if (PyUnicode_READY(to))
654 return -1;
655
Victor Stinnerff9e50f2011-09-28 22:17:19 +0200656 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200657 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
658 PyErr_Format(PyExc_ValueError,
659 "Cannot write %zi characters at %zi "
660 "in a string of %zi characters",
661 how_many, to_start, PyUnicode_GET_LENGTH(to));
662 return -1;
663 }
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200664 if (how_many == 0)
665 return 0;
666
Victor Stinnercd9950f2011-10-02 00:34:53 +0200667 if (_PyUnicode_Dirty(to))
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200668 return -1;
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200670 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200671 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200673 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200674
675 if (from_kind == to_kind) {
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200676 /* fast path */
Victor Stinnera0702ab2011-09-29 14:14:38 +0200677 Py_MEMCPY((char*)to_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200678 + PyUnicode_KIND_SIZE(to_kind, to_start),
Victor Stinnera0702ab2011-09-29 14:14:38 +0200679 (char*)from_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200680 + PyUnicode_KIND_SIZE(from_kind, from_start),
681 PyUnicode_KIND_SIZE(to_kind, how_many));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200682 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200683 else if (from_kind == PyUnicode_1BYTE_KIND
684 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200685 {
686 _PyUnicode_CONVERT_BYTES(
687 Py_UCS1, Py_UCS2,
688 PyUnicode_1BYTE_DATA(from) + from_start,
689 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
690 PyUnicode_2BYTE_DATA(to) + to_start
691 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200692 }
Victor Stinner157f83f2011-09-28 21:41:31 +0200693 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200694 && to_kind == PyUnicode_4BYTE_KIND)
695 {
696 _PyUnicode_CONVERT_BYTES(
697 Py_UCS1, Py_UCS4,
698 PyUnicode_1BYTE_DATA(from) + from_start,
699 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
700 PyUnicode_4BYTE_DATA(to) + to_start
701 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200702 }
703 else if (from_kind == PyUnicode_2BYTE_KIND
704 && to_kind == PyUnicode_4BYTE_KIND)
705 {
706 _PyUnicode_CONVERT_BYTES(
707 Py_UCS2, Py_UCS4,
708 PyUnicode_2BYTE_DATA(from) + from_start,
709 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
710 PyUnicode_4BYTE_DATA(to) + to_start
711 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200712 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200713 else {
714 int invalid_kinds;
715 if (from_kind > to_kind) {
716 /* slow path to check for character overflow */
717 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
718 Py_UCS4 ch, maxchar;
719 Py_ssize_t i;
720
721 maxchar = 0;
722 invalid_kinds = 0;
723 for (i=0; i < how_many; i++) {
724 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
725 if (ch > maxchar) {
726 maxchar = ch;
727 if (maxchar > to_maxchar) {
728 invalid_kinds = 1;
729 break;
730 }
731 }
732 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
733 }
734 }
735 else
736 invalid_kinds = 1;
737 if (invalid_kinds) {
738 PyErr_Format(PyExc_ValueError,
739 "Cannot copy UCS%u characters "
740 "into a string of UCS%u characters",
741 1 << (from_kind - 1),
742 1 << (to_kind -1));
743 return -1;
744 }
745 }
746 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200747}
748
Victor Stinner17222162011-09-28 22:15:37 +0200749/* Find the maximum code point and count the number of surrogate pairs so a
750 correct string length can be computed before converting a string to UCS4.
751 This function counts single surrogates as a character and not as a pair.
752
753 Return 0 on success, or -1 on error. */
754static int
755find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
756 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200757{
758 const wchar_t *iter;
759
Victor Stinnerc53be962011-10-02 21:33:54 +0200760 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200761 if (num_surrogates == NULL || maxchar == NULL) {
762 PyErr_SetString(PyExc_SystemError,
763 "unexpected NULL arguments to "
764 "PyUnicode_FindMaxCharAndNumSurrogatePairs");
765 return -1;
766 }
767
768 *num_surrogates = 0;
769 *maxchar = 0;
770
771 for (iter = begin; iter < end; ) {
772 if (*iter > *maxchar)
773 *maxchar = *iter;
774#if SIZEOF_WCHAR_T == 2
775 if (*iter >= 0xD800 && *iter <= 0xDBFF
776 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
777 {
778 Py_UCS4 surrogate_val;
779 surrogate_val = (((iter[0] & 0x3FF)<<10)
780 | (iter[1] & 0x3FF)) + 0x10000;
781 ++(*num_surrogates);
782 if (surrogate_val > *maxchar)
783 *maxchar = surrogate_val;
784 iter += 2;
785 }
786 else
787 iter++;
788#else
789 iter++;
790#endif
791 }
792 return 0;
793}
794
795#ifdef Py_DEBUG
796int unicode_ready_calls = 0;
797#endif
798
799int
Victor Stinnerd8f65102011-09-29 19:43:17 +0200800_PyUnicode_Ready(PyObject *obj)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801{
Victor Stinnerd8f65102011-09-29 19:43:17 +0200802 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200803 wchar_t *end;
804 Py_UCS4 maxchar = 0;
805 Py_ssize_t num_surrogates;
806#if SIZEOF_WCHAR_T == 2
807 Py_ssize_t length_wo_surrogates;
808#endif
809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200810 /* _PyUnicode_Ready() is only intented for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +0200811 strings were created using _PyObject_New() and where no canonical
812 representation (the str field) has been set yet aka strings
813 which are not yet ready. */
814 assert(PyUnicode_Check(obj));
815 assert(!PyUnicode_IS_READY(obj));
816 assert(!PyUnicode_IS_COMPACT(obj));
817 assert(_PyUnicode_KIND(obj) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200818 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +0200819 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +0200821 /* Actually, it should neither be interned nor be anything else: */
822 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200823
824#ifdef Py_DEBUG
825 ++unicode_ready_calls;
826#endif
827
828 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +0200829 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +0200830 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200831 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832
833 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +0200834 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
835 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200836 PyErr_NoMemory();
837 return -1;
838 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200839 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200840 _PyUnicode_WSTR(unicode), end,
841 PyUnicode_1BYTE_DATA(unicode));
842 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
843 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
844 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
845 if (maxchar < 128) {
Victor Stinnerc3c74152011-10-02 20:39:55 +0200846 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200847 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200848 }
849 else {
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200850 _PyUnicode_UTF8(unicode) = NULL;
851 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200852 }
853 PyObject_FREE(_PyUnicode_WSTR(unicode));
854 _PyUnicode_WSTR(unicode) = NULL;
855 _PyUnicode_WSTR_LENGTH(unicode) = 0;
856 }
857 /* In this case we might have to convert down from 4-byte native
858 wchar_t to 2-byte unicode. */
859 else if (maxchar < 65536) {
860 assert(num_surrogates == 0 &&
861 "FindMaxCharAndNumSurrogatePairs() messed up");
862
Victor Stinner506f5922011-09-28 22:34:18 +0200863#if SIZEOF_WCHAR_T == 2
864 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +0200865 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +0200866 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
867 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
868 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200869 _PyUnicode_UTF8(unicode) = NULL;
870 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +0200871#else
872 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +0200873 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +0200874 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +0200875 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +0200876 PyErr_NoMemory();
877 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200878 }
Victor Stinner506f5922011-09-28 22:34:18 +0200879 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
880 _PyUnicode_WSTR(unicode), end,
881 PyUnicode_2BYTE_DATA(unicode));
882 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
883 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
884 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200885 _PyUnicode_UTF8(unicode) = NULL;
886 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +0200887 PyObject_FREE(_PyUnicode_WSTR(unicode));
888 _PyUnicode_WSTR(unicode) = NULL;
889 _PyUnicode_WSTR_LENGTH(unicode) = 0;
890#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200891 }
892 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
893 else {
894#if SIZEOF_WCHAR_T == 2
895 /* in case the native representation is 2-bytes, we need to allocate a
896 new normalized 4-byte version. */
897 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200898 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
899 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 PyErr_NoMemory();
901 return -1;
902 }
903 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
904 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200905 _PyUnicode_UTF8(unicode) = NULL;
906 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinnerc53be962011-10-02 21:33:54 +0200907 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908 PyObject_FREE(_PyUnicode_WSTR(unicode));
909 _PyUnicode_WSTR(unicode) = NULL;
910 _PyUnicode_WSTR_LENGTH(unicode) = 0;
911#else
912 assert(num_surrogates == 0);
913
Victor Stinnerc3c74152011-10-02 20:39:55 +0200914 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200915 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200916 _PyUnicode_UTF8(unicode) = NULL;
917 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200918 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
919#endif
920 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
921 }
922 _PyUnicode_STATE(unicode).ready = 1;
923 return 0;
924}
925
Alexander Belopolsky40018472011-02-26 01:02:56 +0000926static void
927unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000928{
Walter Dörwald16807132007-05-25 13:52:07 +0000929 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000930 case SSTATE_NOT_INTERNED:
931 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000932
Benjamin Peterson29060642009-01-31 22:14:21 +0000933 case SSTATE_INTERNED_MORTAL:
934 /* revive dead object temporarily for DelItem */
935 Py_REFCNT(unicode) = 3;
936 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
937 Py_FatalError(
938 "deletion of interned string failed");
939 break;
Walter Dörwald16807132007-05-25 13:52:07 +0000940
Benjamin Peterson29060642009-01-31 22:14:21 +0000941 case SSTATE_INTERNED_IMMORTAL:
942 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +0000943
Benjamin Peterson29060642009-01-31 22:14:21 +0000944 default:
945 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +0000946 }
947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200948 if (_PyUnicode_WSTR(unicode) &&
949 (!PyUnicode_IS_READY(unicode) ||
950 _PyUnicode_WSTR(unicode) != PyUnicode_DATA(unicode)))
951 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200952 if (!PyUnicode_IS_COMPACT_ASCII(unicode)
953 && _PyUnicode_UTF8(unicode)
954 && _PyUnicode_UTF8(unicode) != PyUnicode_DATA(unicode))
955 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956
957 if (PyUnicode_IS_COMPACT(unicode)) {
958 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000959 }
960 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +0200961 if (_PyUnicode_DATA_ANY(unicode))
962 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +0000963 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +0000964 }
965}
966
Alexander Belopolsky40018472011-02-26 01:02:56 +0000967static int
968_PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000969{
970 register PyUnicodeObject *v;
971
972 /* Argument checks */
973 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000974 PyErr_BadInternalCall();
975 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000976 }
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +0000977 v = *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978 if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0 ||
979 PyUnicode_IS_COMPACT(v) || _PyUnicode_WSTR(v) == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000980 PyErr_BadInternalCall();
981 return -1;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000982 }
983
984 /* Resizing unicode_empty and single character objects is not
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985 possible since these are being shared.
986 The same goes for new-representation unicode objects or objects which
987 have already been readied.
988 For these, we simply return a fresh copy with the same Unicode content.
989 */
990 if ((_PyUnicode_WSTR_LENGTH(v) != length &&
991 (v == unicode_empty || _PyUnicode_WSTR_LENGTH(v) == 1)) ||
992 PyUnicode_IS_COMPACT(v) || v->data.any) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000993 PyUnicodeObject *w = _PyUnicode_New(length);
994 if (w == NULL)
995 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(v),
997 length < _PyUnicode_WSTR_LENGTH(v) ? length : _PyUnicode_WSTR_LENGTH(v));
Benjamin Peterson29060642009-01-31 22:14:21 +0000998 Py_DECREF(*unicode);
999 *unicode = w;
1000 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001001 }
1002
1003 /* Note that we don't have to modify *unicode for unshared Unicode
1004 objects, since we can modify them in-place. */
1005 return unicode_resize(v, length);
1006}
1007
Alexander Belopolsky40018472011-02-26 01:02:56 +00001008int
1009PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001010{
1011 return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
1012}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001013
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001014static PyObject*
1015get_latin1_char(unsigned char ch)
1016{
Victor Stinnera464fc12011-10-02 20:39:30 +02001017 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001018 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001019 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001020 if (!unicode)
1021 return NULL;
1022 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
1023 unicode_latin1[ch] = unicode;
1024 }
1025 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001026 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001027}
1028
Alexander Belopolsky40018472011-02-26 01:02:56 +00001029PyObject *
1030PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001031{
1032 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033 Py_UCS4 maxchar = 0;
1034 Py_ssize_t num_surrogates;
1035
1036 if (u == NULL)
1037 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001038
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001039 /* If the Unicode data is known at construction time, we can apply
1040 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042 /* Optimization for empty strings */
1043 if (size == 0 && unicode_empty != NULL) {
1044 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001045 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001046 }
Tim Petersced69f82003-09-16 20:30:58 +00001047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 /* Single character Unicode objects in the Latin-1 range are
1049 shared when using this constructor */
1050 if (size == 1 && *u < 256)
1051 return get_latin1_char((unsigned char)*u);
1052
1053 /* If not empty and not single character, copy the Unicode data
1054 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001055 if (find_maxchar_surrogates(u, u + size,
1056 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 return NULL;
1058
1059 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1060 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001061 if (!unicode)
1062 return NULL;
1063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 switch (PyUnicode_KIND(unicode)) {
1065 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001066 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001067 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1068 break;
1069 case PyUnicode_2BYTE_KIND:
1070#if Py_UNICODE_SIZE == 2
1071 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1072#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001073 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1075#endif
1076 break;
1077 case PyUnicode_4BYTE_KIND:
1078#if SIZEOF_WCHAR_T == 2
1079 /* This is the only case which has to process surrogates, thus
1080 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001081 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001082#else
1083 assert(num_surrogates == 0);
1084 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1085#endif
1086 break;
1087 default:
1088 assert(0 && "Impossible state");
1089 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001090
1091 return (PyObject *)unicode;
1092}
1093
Alexander Belopolsky40018472011-02-26 01:02:56 +00001094PyObject *
1095PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001096{
1097 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001098
Benjamin Peterson14339b62009-01-31 16:36:08 +00001099 if (size < 0) {
1100 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001101 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001102 return NULL;
1103 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001104
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001105 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001106 some optimizations which share commonly used objects.
1107 Also, this means the input must be UTF-8, so fall back to the
1108 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001109 if (u != NULL) {
1110
Benjamin Peterson29060642009-01-31 22:14:21 +00001111 /* Optimization for empty strings */
1112 if (size == 0 && unicode_empty != NULL) {
1113 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001114 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001115 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001116
1117 /* Single characters are shared when using this constructor.
1118 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 if (size == 1 && Py_CHARMASK(*u) < 128)
1120 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001121
1122 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001123 }
1124
Walter Dörwald55507312007-05-18 13:12:10 +00001125 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001126 if (!unicode)
1127 return NULL;
1128
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001129 return (PyObject *)unicode;
1130}
1131
Alexander Belopolsky40018472011-02-26 01:02:56 +00001132PyObject *
1133PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001134{
1135 size_t size = strlen(u);
1136 if (size > PY_SSIZE_T_MAX) {
1137 PyErr_SetString(PyExc_OverflowError, "input too long");
1138 return NULL;
1139 }
1140
1141 return PyUnicode_FromStringAndSize(u, size);
1142}
1143
Victor Stinnere57b1c02011-09-28 22:20:48 +02001144static PyObject*
1145_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001146{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 PyObject *res;
1148 unsigned char max = 127;
1149 Py_ssize_t i;
1150 for (i = 0; i < size; i++) {
1151 if (u[i] & 0x80) {
1152 max = 255;
1153 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001154 }
1155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156 res = PyUnicode_New(size, max);
1157 if (!res)
1158 return NULL;
1159 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
1160 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001161}
1162
Victor Stinnere57b1c02011-09-28 22:20:48 +02001163static PyObject*
1164_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165{
1166 PyObject *res;
1167 Py_UCS2 max = 0;
1168 Py_ssize_t i;
1169 for (i = 0; i < size; i++)
1170 if (u[i] > max)
1171 max = u[i];
1172 res = PyUnicode_New(size, max);
1173 if (!res)
1174 return NULL;
1175 if (max >= 256)
1176 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1177 else
1178 for (i = 0; i < size; i++)
1179 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
1180 return res;
1181}
1182
Victor Stinnere57b1c02011-09-28 22:20:48 +02001183static PyObject*
1184_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001185{
1186 PyObject *res;
1187 Py_UCS4 max = 0;
1188 Py_ssize_t i;
1189 for (i = 0; i < size; i++)
1190 if (u[i] > max)
1191 max = u[i];
1192 res = PyUnicode_New(size, max);
1193 if (!res)
1194 return NULL;
1195 if (max >= 0x10000)
1196 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1197 else {
1198 int kind = PyUnicode_KIND(res);
1199 void *data = PyUnicode_DATA(res);
1200 for (i = 0; i < size; i++)
1201 PyUnicode_WRITE(kind, data, i, u[i]);
1202 }
1203 return res;
1204}
1205
1206PyObject*
1207PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1208{
1209 switch(kind) {
1210 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001211 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001212 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001213 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001214 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001215 return _PyUnicode_FromUCS4(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216 }
Victor Stinner202b62b2011-10-01 23:48:37 +02001217 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218 return NULL;
1219}
1220
Victor Stinner034f6cf2011-09-30 02:26:44 +02001221PyObject*
1222PyUnicode_Copy(PyObject *unicode)
1223{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001224 Py_ssize_t size;
1225 PyObject *copy;
1226 void *data;
1227
Victor Stinner034f6cf2011-09-30 02:26:44 +02001228 if (!PyUnicode_Check(unicode)) {
1229 PyErr_BadInternalCall();
1230 return NULL;
1231 }
1232 if (PyUnicode_READY(unicode))
1233 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001234
1235 size = PyUnicode_GET_LENGTH(unicode);
1236 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1237 if (!copy)
1238 return NULL;
1239 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1240
1241 data = PyUnicode_DATA(unicode);
1242 switch (PyUnicode_KIND(unicode))
1243 {
1244 case PyUnicode_1BYTE_KIND:
1245 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1246 break;
1247 case PyUnicode_2BYTE_KIND:
1248 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1249 break;
1250 case PyUnicode_4BYTE_KIND:
1251 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1252 break;
1253 default:
1254 assert(0);
1255 break;
1256 }
1257 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001258}
1259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260
Victor Stinnerbc603d12011-10-02 01:00:40 +02001261/* Widen Unicode objects to larger buffers. Don't write terminating null
1262 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263
1264void*
1265_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1266{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001267 Py_ssize_t len;
1268 void *result;
1269 unsigned int skind;
1270
1271 if (PyUnicode_READY(s))
1272 return NULL;
1273
1274 len = PyUnicode_GET_LENGTH(s);
1275 skind = PyUnicode_KIND(s);
1276 if (skind >= kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001277 PyErr_SetString(PyExc_RuntimeError, "invalid widening attempt");
1278 return NULL;
1279 }
1280 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001281 case PyUnicode_2BYTE_KIND:
1282 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1283 if (!result)
1284 return PyErr_NoMemory();
1285 assert(skind == PyUnicode_1BYTE_KIND);
1286 _PyUnicode_CONVERT_BYTES(
1287 Py_UCS1, Py_UCS2,
1288 PyUnicode_1BYTE_DATA(s),
1289 PyUnicode_1BYTE_DATA(s) + len,
1290 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001291 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001292 case PyUnicode_4BYTE_KIND:
1293 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1294 if (!result)
1295 return PyErr_NoMemory();
1296 if (skind == PyUnicode_2BYTE_KIND) {
1297 _PyUnicode_CONVERT_BYTES(
1298 Py_UCS2, Py_UCS4,
1299 PyUnicode_2BYTE_DATA(s),
1300 PyUnicode_2BYTE_DATA(s) + len,
1301 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001302 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001303 else {
1304 assert(skind == PyUnicode_1BYTE_KIND);
1305 _PyUnicode_CONVERT_BYTES(
1306 Py_UCS1, Py_UCS4,
1307 PyUnicode_1BYTE_DATA(s),
1308 PyUnicode_1BYTE_DATA(s) + len,
1309 result);
1310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001312 default:
1313 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001315 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 return NULL;
1317}
1318
1319static Py_UCS4*
1320as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1321 int copy_null)
1322{
1323 int kind;
1324 void *data;
1325 Py_ssize_t len, targetlen;
1326 if (PyUnicode_READY(string) == -1)
1327 return NULL;
1328 kind = PyUnicode_KIND(string);
1329 data = PyUnicode_DATA(string);
1330 len = PyUnicode_GET_LENGTH(string);
1331 targetlen = len;
1332 if (copy_null)
1333 targetlen++;
1334 if (!target) {
1335 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1336 PyErr_NoMemory();
1337 return NULL;
1338 }
1339 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1340 if (!target) {
1341 PyErr_NoMemory();
1342 return NULL;
1343 }
1344 }
1345 else {
1346 if (targetsize < targetlen) {
1347 PyErr_Format(PyExc_SystemError,
1348 "string is longer than the buffer");
1349 if (copy_null && 0 < targetsize)
1350 target[0] = 0;
1351 return NULL;
1352 }
1353 }
1354 if (kind != PyUnicode_4BYTE_KIND) {
1355 Py_ssize_t i;
1356 for (i = 0; i < len; i++)
1357 target[i] = PyUnicode_READ(kind, data, i);
1358 }
1359 else
1360 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1361 if (copy_null)
1362 target[len] = 0;
1363 return target;
1364}
1365
1366Py_UCS4*
1367PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1368 int copy_null)
1369{
1370 if (target == NULL || targetsize < 1) {
1371 PyErr_BadInternalCall();
1372 return NULL;
1373 }
1374 return as_ucs4(string, target, targetsize, copy_null);
1375}
1376
1377Py_UCS4*
1378PyUnicode_AsUCS4Copy(PyObject *string)
1379{
1380 return as_ucs4(string, NULL, 0, 1);
1381}
1382
1383#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001384
Alexander Belopolsky40018472011-02-26 01:02:56 +00001385PyObject *
1386PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001387{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001388 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001389 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001391 PyErr_BadInternalCall();
1392 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001393 }
1394
Martin v. Löwis790465f2008-04-05 20:41:37 +00001395 if (size == -1) {
1396 size = wcslen(w);
1397 }
1398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001400}
1401
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001403
Walter Dörwald346737f2007-05-31 10:44:43 +00001404static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001405makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1406 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001407{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001408 *fmt++ = '%';
1409 if (width) {
1410 if (zeropad)
1411 *fmt++ = '0';
1412 fmt += sprintf(fmt, "%d", width);
1413 }
1414 if (precision)
1415 fmt += sprintf(fmt, ".%d", precision);
1416 if (longflag)
1417 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001418 else if (longlongflag) {
1419 /* longlongflag should only ever be nonzero on machines with
1420 HAVE_LONG_LONG defined */
1421#ifdef HAVE_LONG_LONG
1422 char *f = PY_FORMAT_LONG_LONG;
1423 while (*f)
1424 *fmt++ = *f++;
1425#else
1426 /* we shouldn't ever get here */
1427 assert(0);
1428 *fmt++ = 'l';
1429#endif
1430 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001431 else if (size_tflag) {
1432 char *f = PY_FORMAT_SIZE_T;
1433 while (*f)
1434 *fmt++ = *f++;
1435 }
1436 *fmt++ = c;
1437 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00001438}
1439
Victor Stinner96865452011-03-01 23:44:09 +00001440/* helper for PyUnicode_FromFormatV() */
1441
1442static const char*
1443parse_format_flags(const char *f,
1444 int *p_width, int *p_precision,
1445 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
1446{
1447 int width, precision, longflag, longlongflag, size_tflag;
1448
1449 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
1450 f++;
1451 width = 0;
1452 while (Py_ISDIGIT((unsigned)*f))
1453 width = (width*10) + *f++ - '0';
1454 precision = 0;
1455 if (*f == '.') {
1456 f++;
1457 while (Py_ISDIGIT((unsigned)*f))
1458 precision = (precision*10) + *f++ - '0';
1459 if (*f == '%') {
1460 /* "%.3%s" => f points to "3" */
1461 f--;
1462 }
1463 }
1464 if (*f == '\0') {
1465 /* bogus format "%.1" => go backward, f points to "1" */
1466 f--;
1467 }
1468 if (p_width != NULL)
1469 *p_width = width;
1470 if (p_precision != NULL)
1471 *p_precision = precision;
1472
1473 /* Handle %ld, %lu, %lld and %llu. */
1474 longflag = 0;
1475 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00001476 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00001477
1478 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00001479 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00001480 longflag = 1;
1481 ++f;
1482 }
1483#ifdef HAVE_LONG_LONG
1484 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00001485 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001486 longlongflag = 1;
1487 f += 2;
1488 }
1489#endif
1490 }
1491 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00001492 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001493 size_tflag = 1;
1494 ++f;
1495 }
1496 if (p_longflag != NULL)
1497 *p_longflag = longflag;
1498 if (p_longlongflag != NULL)
1499 *p_longlongflag = longlongflag;
1500 if (p_size_tflag != NULL)
1501 *p_size_tflag = size_tflag;
1502 return f;
1503}
1504
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001505/* maximum number of characters required for output of %ld. 21 characters
1506 allows for 64-bit integers (in decimal) and an optional sign. */
1507#define MAX_LONG_CHARS 21
1508/* maximum number of characters required for output of %lld.
1509 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
1510 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
1511#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
1512
Walter Dörwaldd2034312007-05-18 16:29:38 +00001513PyObject *
1514PyUnicode_FromFormatV(const char *format, va_list vargs)
1515{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001516 va_list count;
1517 Py_ssize_t callcount = 0;
1518 PyObject **callresults = NULL;
1519 PyObject **callresult = NULL;
1520 Py_ssize_t n = 0;
1521 int width = 0;
1522 int precision = 0;
1523 int zeropad;
1524 const char* f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001525 PyUnicodeObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001526 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001527 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001528 Py_UCS4 maxchar = 127; /* result is ASCII by default */
1529 Py_UCS4 argmaxchar;
1530 Py_ssize_t numbersize = 0;
1531 char *numberresults = NULL;
1532 char *numberresult = NULL;
1533 Py_ssize_t i;
1534 int kind;
1535 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001536
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001537 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001538 /* step 1: count the number of %S/%R/%A/%s format specifications
1539 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
1540 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001541 * result in an array)
1542 * also esimate a upper bound for all the number formats in the string,
1543 * numbers will be formated in step 3 and be keept in a '\0'-separated
1544 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00001545 for (f = format; *f; f++) {
1546 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001547 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
1549 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
1550 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
1551 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001554#ifdef HAVE_LONG_LONG
1555 if (longlongflag) {
1556 if (width < MAX_LONG_LONG_CHARS)
1557 width = MAX_LONG_LONG_CHARS;
1558 }
1559 else
1560#endif
1561 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
1562 including sign. Decimal takes the most space. This
1563 isn't enough for octal. If a width is specified we
1564 need more (which we allocate later). */
1565 if (width < MAX_LONG_CHARS)
1566 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001567
1568 /* account for the size + '\0' to separate numbers
1569 inside of the numberresults buffer */
1570 numbersize += (width + 1);
1571 }
1572 }
1573 else if ((unsigned char)*f > 127) {
1574 PyErr_Format(PyExc_ValueError,
1575 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
1576 "string, got a non-ASCII byte: 0x%02x",
1577 (unsigned char)*f);
1578 return NULL;
1579 }
1580 }
1581 /* step 2: allocate memory for the results of
1582 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
1583 if (callcount) {
1584 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
1585 if (!callresults) {
1586 PyErr_NoMemory();
1587 return NULL;
1588 }
1589 callresult = callresults;
1590 }
1591 /* step 2.5: allocate memory for the results of formating numbers */
1592 if (numbersize) {
1593 numberresults = PyObject_Malloc(numbersize);
1594 if (!numberresults) {
1595 PyErr_NoMemory();
1596 goto fail;
1597 }
1598 numberresult = numberresults;
1599 }
1600
1601 /* step 3: format numbers and figure out how large a buffer we need */
1602 for (f = format; *f; f++) {
1603 if (*f == '%') {
1604 const char* p;
1605 int longflag;
1606 int longlongflag;
1607 int size_tflag;
1608 int numprinted;
1609
1610 p = f;
1611 zeropad = (f[1] == '0');
1612 f = parse_format_flags(f, &width, &precision,
1613 &longflag, &longlongflag, &size_tflag);
1614 switch (*f) {
1615 case 'c':
1616 {
1617 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001618 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619 n++;
1620 break;
1621 }
1622 case '%':
1623 n++;
1624 break;
1625 case 'i':
1626 case 'd':
1627 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1628 width, precision, *f);
1629 if (longflag)
1630 numprinted = sprintf(numberresult, fmt,
1631 va_arg(count, long));
1632#ifdef HAVE_LONG_LONG
1633 else if (longlongflag)
1634 numprinted = sprintf(numberresult, fmt,
1635 va_arg(count, PY_LONG_LONG));
1636#endif
1637 else if (size_tflag)
1638 numprinted = sprintf(numberresult, fmt,
1639 va_arg(count, Py_ssize_t));
1640 else
1641 numprinted = sprintf(numberresult, fmt,
1642 va_arg(count, int));
1643 n += numprinted;
1644 /* advance by +1 to skip over the '\0' */
1645 numberresult += (numprinted + 1);
1646 assert(*(numberresult - 1) == '\0');
1647 assert(*(numberresult - 2) != '\0');
1648 assert(numprinted >= 0);
1649 assert(numberresult <= numberresults + numbersize);
1650 break;
1651 case 'u':
1652 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1653 width, precision, 'u');
1654 if (longflag)
1655 numprinted = sprintf(numberresult, fmt,
1656 va_arg(count, unsigned long));
1657#ifdef HAVE_LONG_LONG
1658 else if (longlongflag)
1659 numprinted = sprintf(numberresult, fmt,
1660 va_arg(count, unsigned PY_LONG_LONG));
1661#endif
1662 else if (size_tflag)
1663 numprinted = sprintf(numberresult, fmt,
1664 va_arg(count, size_t));
1665 else
1666 numprinted = sprintf(numberresult, fmt,
1667 va_arg(count, unsigned int));
1668 n += numprinted;
1669 numberresult += (numprinted + 1);
1670 assert(*(numberresult - 1) == '\0');
1671 assert(*(numberresult - 2) != '\0');
1672 assert(numprinted >= 0);
1673 assert(numberresult <= numberresults + numbersize);
1674 break;
1675 case 'x':
1676 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
1677 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
1678 n += numprinted;
1679 numberresult += (numprinted + 1);
1680 assert(*(numberresult - 1) == '\0');
1681 assert(*(numberresult - 2) != '\0');
1682 assert(numprinted >= 0);
1683 assert(numberresult <= numberresults + numbersize);
1684 break;
1685 case 'p':
1686 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
1687 /* %p is ill-defined: ensure leading 0x. */
1688 if (numberresult[1] == 'X')
1689 numberresult[1] = 'x';
1690 else if (numberresult[1] != 'x') {
1691 memmove(numberresult + 2, numberresult,
1692 strlen(numberresult) + 1);
1693 numberresult[0] = '0';
1694 numberresult[1] = 'x';
1695 numprinted += 2;
1696 }
1697 n += numprinted;
1698 numberresult += (numprinted + 1);
1699 assert(*(numberresult - 1) == '\0');
1700 assert(*(numberresult - 2) != '\0');
1701 assert(numprinted >= 0);
1702 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001703 break;
1704 case 's':
1705 {
1706 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00001707 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001708 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
1709 if (!str)
1710 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001711 /* since PyUnicode_DecodeUTF8 returns already flexible
1712 unicode objects, there is no need to call ready on them */
1713 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001714 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001716 /* Remember the str and switch to the next slot */
1717 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001718 break;
1719 }
1720 case 'U':
1721 {
1722 PyObject *obj = va_arg(count, PyObject *);
1723 assert(obj && PyUnicode_Check(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 if (PyUnicode_READY(obj) == -1)
1725 goto fail;
1726 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001727 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001729 break;
1730 }
1731 case 'V':
1732 {
1733 PyObject *obj = va_arg(count, PyObject *);
1734 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001735 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001736 assert(obj || str);
1737 assert(!obj || PyUnicode_Check(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00001738 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 if (PyUnicode_READY(obj) == -1)
1740 goto fail;
1741 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001742 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001743 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001744 *callresult++ = NULL;
1745 }
1746 else {
1747 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
1748 if (!str_obj)
1749 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001751 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001753 *callresult++ = str_obj;
1754 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001755 break;
1756 }
1757 case 'S':
1758 {
1759 PyObject *obj = va_arg(count, PyObject *);
1760 PyObject *str;
1761 assert(obj);
1762 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001763 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001764 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001766 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001768 /* Remember the str and switch to the next slot */
1769 *callresult++ = str;
1770 break;
1771 }
1772 case 'R':
1773 {
1774 PyObject *obj = va_arg(count, PyObject *);
1775 PyObject *repr;
1776 assert(obj);
1777 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001779 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001781 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001783 /* Remember the repr and switch to the next slot */
1784 *callresult++ = repr;
1785 break;
1786 }
1787 case 'A':
1788 {
1789 PyObject *obj = va_arg(count, PyObject *);
1790 PyObject *ascii;
1791 assert(obj);
1792 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001793 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001794 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001795 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001796 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001798 /* Remember the repr and switch to the next slot */
1799 *callresult++ = ascii;
1800 break;
1801 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001802 default:
1803 /* if we stumble upon an unknown
1804 formatting code, copy the rest of
1805 the format string to the output
1806 string. (we cannot just skip the
1807 code, since there's no way to know
1808 what's in the argument list) */
1809 n += strlen(p);
1810 goto expand;
1811 }
1812 } else
1813 n++;
1814 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001815 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001816 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00001818 we don't have to resize the string.
1819 There can be no errors beyond this point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001820 string = (PyUnicodeObject *)PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001821 if (!string)
1822 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001823 kind = PyUnicode_KIND(string);
1824 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001825 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001829 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001830 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00001831
1832 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
1834 /* checking for == because the last argument could be a empty
1835 string, which causes i to point to end, the assert at the end of
1836 the loop */
1837 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00001838
Benjamin Peterson14339b62009-01-31 16:36:08 +00001839 switch (*f) {
1840 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00001841 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001842 const int ordinal = va_arg(vargs, int);
1843 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001844 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00001845 }
Victor Stinner6d970f42011-03-02 00:04:25 +00001846 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001847 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001848 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001849 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 case 'p':
1851 /* unused, since we already have the result */
1852 if (*f == 'p')
1853 (void) va_arg(vargs, void *);
1854 else
1855 (void) va_arg(vargs, int);
1856 /* extract the result from numberresults and append. */
1857 for (; *numberresult; ++i, ++numberresult)
1858 PyUnicode_WRITE(kind, data, i, *numberresult);
1859 /* skip over the separating '\0' */
1860 assert(*numberresult == '\0');
1861 numberresult++;
1862 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 break;
1864 case 's':
1865 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001866 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001868 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001869 size = PyUnicode_GET_LENGTH(*callresult);
1870 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02001871 if (PyUnicode_CopyCharacters((PyObject*)string, i,
1872 *callresult, 0,
1873 size) < 0)
1874 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001876 /* We're done with the unicode()/repr() => forget it */
1877 Py_DECREF(*callresult);
1878 /* switch to next unicode()/repr() result */
1879 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001880 break;
1881 }
1882 case 'U':
1883 {
1884 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001885 Py_ssize_t size;
1886 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
1887 size = PyUnicode_GET_LENGTH(obj);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02001888 if (PyUnicode_CopyCharacters((PyObject*)string, i,
1889 obj, 0,
1890 size) < 0)
1891 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001892 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001893 break;
1894 }
1895 case 'V':
1896 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001898 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001899 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001900 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 size = PyUnicode_GET_LENGTH(obj);
1902 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02001903 if (PyUnicode_CopyCharacters((PyObject*)string, i,
1904 obj, 0,
1905 size) < 0)
1906 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001908 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001909 size = PyUnicode_GET_LENGTH(*callresult);
1910 assert(PyUnicode_KIND(*callresult) <=
1911 PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02001912 if (PyUnicode_CopyCharacters((PyObject*)string, i,
1913 *callresult,
1914 0, size) < 0)
1915 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001916 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00001917 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001918 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00001919 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001920 break;
1921 }
1922 case 'S':
1923 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00001924 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00001925 {
Benjamin Peterson14339b62009-01-31 16:36:08 +00001926 /* unused, since we already have the result */
1927 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001928 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02001929 if (PyUnicode_CopyCharacters((PyObject*)string, i,
1930 *callresult, 0,
1931 PyUnicode_GET_LENGTH(*callresult)) < 0)
1932 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001933 i += PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001934 /* We're done with the unicode()/repr() => forget it */
1935 Py_DECREF(*callresult);
1936 /* switch to next unicode()/repr() result */
1937 ++callresult;
1938 break;
1939 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001940 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001941 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00001942 break;
1943 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944 for (; *p; ++p, ++i)
1945 PyUnicode_WRITE(kind, data, i, *p);
1946 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00001947 goto end;
1948 }
Victor Stinner1205f272010-09-11 00:54:47 +00001949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 else {
1951 assert(i < PyUnicode_GET_LENGTH(string));
1952 PyUnicode_WRITE(kind, data, i++, *f);
1953 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001955 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00001956
Benjamin Peterson29060642009-01-31 22:14:21 +00001957 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001958 if (callresults)
1959 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960 if (numberresults)
1961 PyObject_Free(numberresults);
1962 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00001963 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00001964 if (callresults) {
1965 PyObject **callresult2 = callresults;
1966 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00001967 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001968 ++callresult2;
1969 }
1970 PyObject_Free(callresults);
1971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001972 if (numberresults)
1973 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001974 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001975}
1976
Walter Dörwaldd2034312007-05-18 16:29:38 +00001977PyObject *
1978PyUnicode_FromFormat(const char *format, ...)
1979{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001980 PyObject* ret;
1981 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001982
1983#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00001984 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001985#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00001986 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001987#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00001988 ret = PyUnicode_FromFormatV(format, vargs);
1989 va_end(vargs);
1990 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001991}
1992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993#ifdef HAVE_WCHAR_H
1994
Victor Stinner5593d8a2010-10-02 11:11:27 +00001995/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
1996 convert a Unicode object to a wide character string.
1997
Victor Stinnerd88d9832011-09-06 02:00:05 +02001998 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00001999 character) required to convert the unicode object. Ignore size argument.
2000
Victor Stinnerd88d9832011-09-06 02:00:05 +02002001 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002002 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002003 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002004static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002005unicode_aswidechar(PyUnicodeObject *unicode,
2006 wchar_t *w,
2007 Py_ssize_t size)
2008{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002009 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 const wchar_t *wstr;
2011
2012 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2013 if (wstr == NULL)
2014 return -1;
2015
Victor Stinner5593d8a2010-10-02 11:11:27 +00002016 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002017 if (size > res)
2018 size = res + 1;
2019 else
2020 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002021 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002022 return res;
2023 }
2024 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002026}
2027
2028Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002029PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002030 wchar_t *w,
2031 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002032{
2033 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002034 PyErr_BadInternalCall();
2035 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002036 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002037 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002038}
2039
Victor Stinner137c34c2010-09-29 10:25:54 +00002040wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002041PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002042 Py_ssize_t *size)
2043{
2044 wchar_t* buffer;
2045 Py_ssize_t buflen;
2046
2047 if (unicode == NULL) {
2048 PyErr_BadInternalCall();
2049 return NULL;
2050 }
2051
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002052 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 if (buflen == -1)
2054 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002055 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002056 PyErr_NoMemory();
2057 return NULL;
2058 }
2059
Victor Stinner137c34c2010-09-29 10:25:54 +00002060 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2061 if (buffer == NULL) {
2062 PyErr_NoMemory();
2063 return NULL;
2064 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002065 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 if (buflen == -1)
2067 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002068 if (size != NULL)
2069 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002070 return buffer;
2071}
2072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002073#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002074
Alexander Belopolsky40018472011-02-26 01:02:56 +00002075PyObject *
2076PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002077{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002079 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002080 PyErr_SetString(PyExc_ValueError,
2081 "chr() arg not in range(0x110000)");
2082 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002083 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002085 if (ordinal < 256)
2086 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 v = PyUnicode_New(1, ordinal);
2089 if (v == NULL)
2090 return NULL;
2091 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
2092 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002093}
2094
Alexander Belopolsky40018472011-02-26 01:02:56 +00002095PyObject *
2096PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002097{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002098 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002099 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002100 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002101 if (PyUnicode_READY(obj))
2102 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002103 Py_INCREF(obj);
2104 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002105 }
2106 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002107 /* For a Unicode subtype that's not a Unicode object,
2108 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002109 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002110 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002111 PyErr_Format(PyExc_TypeError,
2112 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002113 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002114 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002115}
2116
Alexander Belopolsky40018472011-02-26 01:02:56 +00002117PyObject *
2118PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002119 const char *encoding,
2120 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002121{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002122 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002123 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002124
Guido van Rossumd57fd912000-03-10 22:53:23 +00002125 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002126 PyErr_BadInternalCall();
2127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002128 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002129
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002130 /* Decoding bytes objects is the most common case and should be fast */
2131 if (PyBytes_Check(obj)) {
2132 if (PyBytes_GET_SIZE(obj) == 0) {
2133 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002134 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002135 }
2136 else {
2137 v = PyUnicode_Decode(
2138 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2139 encoding, errors);
2140 }
2141 return v;
2142 }
2143
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002144 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002145 PyErr_SetString(PyExc_TypeError,
2146 "decoding str is not supported");
2147 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002148 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002149
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002150 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2151 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2152 PyErr_Format(PyExc_TypeError,
2153 "coercing to str: need bytes, bytearray "
2154 "or buffer-like object, %.80s found",
2155 Py_TYPE(obj)->tp_name);
2156 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002157 }
Tim Petersced69f82003-09-16 20:30:58 +00002158
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002159 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002160 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002161 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002162 }
Tim Petersced69f82003-09-16 20:30:58 +00002163 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002164 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002165
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002166 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002167 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002168}
2169
Victor Stinner600d3be2010-06-10 12:00:55 +00002170/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002171 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2172 1 on success. */
2173static int
2174normalize_encoding(const char *encoding,
2175 char *lower,
2176 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002177{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002178 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002179 char *l;
2180 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002181
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002182 e = encoding;
2183 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002184 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002185 while (*e) {
2186 if (l == l_end)
2187 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002188 if (Py_ISUPPER(*e)) {
2189 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002190 }
2191 else if (*e == '_') {
2192 *l++ = '-';
2193 e++;
2194 }
2195 else {
2196 *l++ = *e++;
2197 }
2198 }
2199 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002200 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002201}
2202
Alexander Belopolsky40018472011-02-26 01:02:56 +00002203PyObject *
2204PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002205 Py_ssize_t size,
2206 const char *encoding,
2207 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002208{
2209 PyObject *buffer = NULL, *unicode;
2210 Py_buffer info;
2211 char lower[11]; /* Enough for any encoding shortcut */
2212
2213 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002214 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002215
2216 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002217 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002218 if ((strcmp(lower, "utf-8") == 0) ||
2219 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002220 return PyUnicode_DecodeUTF8(s, size, errors);
2221 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002222 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002223 (strcmp(lower, "iso-8859-1") == 0))
2224 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002225#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002226 else if (strcmp(lower, "mbcs") == 0)
2227 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002228#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002229 else if (strcmp(lower, "ascii") == 0)
2230 return PyUnicode_DecodeASCII(s, size, errors);
2231 else if (strcmp(lower, "utf-16") == 0)
2232 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2233 else if (strcmp(lower, "utf-32") == 0)
2234 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002236
2237 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002238 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002239 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002240 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002241 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002242 if (buffer == NULL)
2243 goto onError;
2244 unicode = PyCodec_Decode(buffer, encoding, errors);
2245 if (unicode == NULL)
2246 goto onError;
2247 if (!PyUnicode_Check(unicode)) {
2248 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002249 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002250 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002251 Py_DECREF(unicode);
2252 goto onError;
2253 }
2254 Py_DECREF(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255 if (PyUnicode_READY(unicode)) {
2256 Py_DECREF(unicode);
2257 return NULL;
2258 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002259 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002260
Benjamin Peterson29060642009-01-31 22:14:21 +00002261 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002262 Py_XDECREF(buffer);
2263 return NULL;
2264}
2265
Alexander Belopolsky40018472011-02-26 01:02:56 +00002266PyObject *
2267PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002268 const char *encoding,
2269 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002270{
2271 PyObject *v;
2272
2273 if (!PyUnicode_Check(unicode)) {
2274 PyErr_BadArgument();
2275 goto onError;
2276 }
2277
2278 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002279 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002280
2281 /* Decode via the codec registry */
2282 v = PyCodec_Decode(unicode, encoding, errors);
2283 if (v == NULL)
2284 goto onError;
2285 return v;
2286
Benjamin Peterson29060642009-01-31 22:14:21 +00002287 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002288 return NULL;
2289}
2290
Alexander Belopolsky40018472011-02-26 01:02:56 +00002291PyObject *
2292PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002293 const char *encoding,
2294 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002295{
2296 PyObject *v;
2297
2298 if (!PyUnicode_Check(unicode)) {
2299 PyErr_BadArgument();
2300 goto onError;
2301 }
2302
2303 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002304 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002305
2306 /* Decode via the codec registry */
2307 v = PyCodec_Decode(unicode, encoding, errors);
2308 if (v == NULL)
2309 goto onError;
2310 if (!PyUnicode_Check(v)) {
2311 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002312 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002313 Py_TYPE(v)->tp_name);
2314 Py_DECREF(v);
2315 goto onError;
2316 }
2317 return v;
2318
Benjamin Peterson29060642009-01-31 22:14:21 +00002319 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002320 return NULL;
2321}
2322
Alexander Belopolsky40018472011-02-26 01:02:56 +00002323PyObject *
2324PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002325 Py_ssize_t size,
2326 const char *encoding,
2327 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002328{
2329 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002330
Guido van Rossumd57fd912000-03-10 22:53:23 +00002331 unicode = PyUnicode_FromUnicode(s, size);
2332 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002333 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002334 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2335 Py_DECREF(unicode);
2336 return v;
2337}
2338
Alexander Belopolsky40018472011-02-26 01:02:56 +00002339PyObject *
2340PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002341 const char *encoding,
2342 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002343{
2344 PyObject *v;
2345
2346 if (!PyUnicode_Check(unicode)) {
2347 PyErr_BadArgument();
2348 goto onError;
2349 }
2350
2351 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002352 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002353
2354 /* Encode via the codec registry */
2355 v = PyCodec_Encode(unicode, encoding, errors);
2356 if (v == NULL)
2357 goto onError;
2358 return v;
2359
Benjamin Peterson29060642009-01-31 22:14:21 +00002360 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002361 return NULL;
2362}
2363
Victor Stinnerad158722010-10-27 00:25:46 +00002364PyObject *
2365PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002366{
Victor Stinner99b95382011-07-04 14:23:54 +02002367#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002368 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2369 PyUnicode_GET_SIZE(unicode),
2370 NULL);
2371#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002373#else
Victor Stinner793b5312011-04-27 00:24:21 +02002374 PyInterpreterState *interp = PyThreadState_GET()->interp;
2375 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2376 cannot use it to encode and decode filenames before it is loaded. Load
2377 the Python codec requires to encode at least its own filename. Use the C
2378 version of the locale codec until the codec registry is initialized and
2379 the Python codec is loaded.
2380
2381 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2382 cannot only rely on it: check also interp->fscodec_initialized for
2383 subinterpreters. */
2384 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002385 return PyUnicode_AsEncodedString(unicode,
2386 Py_FileSystemDefaultEncoding,
2387 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002388 }
2389 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002390 /* locale encoding with surrogateescape */
2391 wchar_t *wchar;
2392 char *bytes;
2393 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002394 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002395
2396 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2397 if (wchar == NULL)
2398 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002399 bytes = _Py_wchar2char(wchar, &error_pos);
2400 if (bytes == NULL) {
2401 if (error_pos != (size_t)-1) {
2402 char *errmsg = strerror(errno);
2403 PyObject *exc = NULL;
2404 if (errmsg == NULL)
2405 errmsg = "Py_wchar2char() failed";
2406 raise_encode_exception(&exc,
2407 "filesystemencoding",
2408 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2409 error_pos, error_pos+1,
2410 errmsg);
2411 Py_XDECREF(exc);
2412 }
2413 else
2414 PyErr_NoMemory();
2415 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002416 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002417 }
2418 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002419
2420 bytes_obj = PyBytes_FromString(bytes);
2421 PyMem_Free(bytes);
2422 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00002423 }
Victor Stinnerad158722010-10-27 00:25:46 +00002424#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00002425}
2426
Alexander Belopolsky40018472011-02-26 01:02:56 +00002427PyObject *
2428PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002429 const char *encoding,
2430 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002431{
2432 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00002433 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00002434
Guido van Rossumd57fd912000-03-10 22:53:23 +00002435 if (!PyUnicode_Check(unicode)) {
2436 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002437 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002438 }
Fred Drakee4315f52000-05-09 19:53:39 +00002439
Victor Stinner2f283c22011-03-02 01:21:46 +00002440 if (encoding == NULL) {
2441 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002443 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00002445 }
Fred Drakee4315f52000-05-09 19:53:39 +00002446
2447 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002448 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002449 if ((strcmp(lower, "utf-8") == 0) ||
2450 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00002451 {
Victor Stinner2f283c22011-03-02 01:21:46 +00002452 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002454 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00002456 }
Victor Stinner37296e82010-06-10 13:36:23 +00002457 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002458 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002459 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002460 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002461#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002462 else if (strcmp(lower, "mbcs") == 0)
2463 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2464 PyUnicode_GET_SIZE(unicode),
2465 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002466#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002467 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002468 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00002469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002470
2471 /* Encode via the codec registry */
2472 v = PyCodec_Encode(unicode, encoding, errors);
2473 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002474 return NULL;
2475
2476 /* The normal path */
2477 if (PyBytes_Check(v))
2478 return v;
2479
2480 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002481 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002482 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002483 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002484
2485 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
2486 "encoder %s returned bytearray instead of bytes",
2487 encoding);
2488 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002489 Py_DECREF(v);
2490 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002491 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002492
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002493 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
2494 Py_DECREF(v);
2495 return b;
2496 }
2497
2498 PyErr_Format(PyExc_TypeError,
2499 "encoder did not return a bytes object (type=%.400s)",
2500 Py_TYPE(v)->tp_name);
2501 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002502 return NULL;
2503}
2504
Alexander Belopolsky40018472011-02-26 01:02:56 +00002505PyObject *
2506PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002507 const char *encoding,
2508 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002509{
2510 PyObject *v;
2511
2512 if (!PyUnicode_Check(unicode)) {
2513 PyErr_BadArgument();
2514 goto onError;
2515 }
2516
2517 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002518 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002519
2520 /* Encode via the codec registry */
2521 v = PyCodec_Encode(unicode, encoding, errors);
2522 if (v == NULL)
2523 goto onError;
2524 if (!PyUnicode_Check(v)) {
2525 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002526 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002527 Py_TYPE(v)->tp_name);
2528 Py_DECREF(v);
2529 goto onError;
2530 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002531 return v;
Tim Petersced69f82003-09-16 20:30:58 +00002532
Benjamin Peterson29060642009-01-31 22:14:21 +00002533 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002534 return NULL;
2535}
2536
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002537PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00002538PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002539 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00002540 return PyUnicode_DecodeFSDefaultAndSize(s, size);
2541}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002542
Christian Heimes5894ba72007-11-04 11:43:14 +00002543PyObject*
2544PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
2545{
Victor Stinner99b95382011-07-04 14:23:54 +02002546#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002547 return PyUnicode_DecodeMBCS(s, size, NULL);
2548#elif defined(__APPLE__)
2549 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
2550#else
Victor Stinner793b5312011-04-27 00:24:21 +02002551 PyInterpreterState *interp = PyThreadState_GET()->interp;
2552 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2553 cannot use it to encode and decode filenames before it is loaded. Load
2554 the Python codec requires to encode at least its own filename. Use the C
2555 version of the locale codec until the codec registry is initialized and
2556 the Python codec is loaded.
2557
2558 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2559 cannot only rely on it: check also interp->fscodec_initialized for
2560 subinterpreters. */
2561 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002562 return PyUnicode_Decode(s, size,
2563 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00002564 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002565 }
2566 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002567 /* locale encoding with surrogateescape */
2568 wchar_t *wchar;
2569 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00002570 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002571
2572 if (s[size] != '\0' || size != strlen(s)) {
2573 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2574 return NULL;
2575 }
2576
Victor Stinner168e1172010-10-16 23:16:16 +00002577 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002578 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00002579 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002580
Victor Stinner168e1172010-10-16 23:16:16 +00002581 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002582 PyMem_Free(wchar);
2583 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002584 }
Victor Stinnerad158722010-10-27 00:25:46 +00002585#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002586}
2587
Martin v. Löwis011e8422009-05-05 04:43:17 +00002588
2589int
2590PyUnicode_FSConverter(PyObject* arg, void* addr)
2591{
2592 PyObject *output = NULL;
2593 Py_ssize_t size;
2594 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002595 if (arg == NULL) {
2596 Py_DECREF(*(PyObject**)addr);
2597 return 1;
2598 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00002599 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00002600 output = arg;
2601 Py_INCREF(output);
2602 }
2603 else {
2604 arg = PyUnicode_FromObject(arg);
2605 if (!arg)
2606 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002607 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002608 Py_DECREF(arg);
2609 if (!output)
2610 return 0;
2611 if (!PyBytes_Check(output)) {
2612 Py_DECREF(output);
2613 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
2614 return 0;
2615 }
2616 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00002617 size = PyBytes_GET_SIZE(output);
2618 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002619 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05002620 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00002621 Py_DECREF(output);
2622 return 0;
2623 }
2624 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002625 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00002626}
2627
2628
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002629int
2630PyUnicode_FSDecoder(PyObject* arg, void* addr)
2631{
2632 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002633 if (arg == NULL) {
2634 Py_DECREF(*(PyObject**)addr);
2635 return 1;
2636 }
2637 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (PyUnicode_READY(arg))
2639 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002640 output = arg;
2641 Py_INCREF(output);
2642 }
2643 else {
2644 arg = PyBytes_FromObject(arg);
2645 if (!arg)
2646 return 0;
2647 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
2648 PyBytes_GET_SIZE(arg));
2649 Py_DECREF(arg);
2650 if (!output)
2651 return 0;
2652 if (!PyUnicode_Check(output)) {
2653 Py_DECREF(output);
2654 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
2655 return 0;
2656 }
2657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
2659 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002660 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2661 Py_DECREF(output);
2662 return 0;
2663 }
2664 *(PyObject**)addr = output;
2665 return Py_CLEANUP_SUPPORTED;
2666}
2667
2668
Martin v. Löwis5b222132007-06-10 09:51:05 +00002669char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002670PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002671{
Christian Heimesf3863112007-11-22 07:46:41 +00002672 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
2674
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00002675 if (!PyUnicode_Check(unicode)) {
2676 PyErr_BadArgument();
2677 return NULL;
2678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002679 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002680 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002681
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002682 if (PyUnicode_UTF8(unicode) == NULL) {
2683 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002684 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
2685 if (bytes == NULL)
2686 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002687 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
2688 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 Py_DECREF(bytes);
2690 return NULL;
2691 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002692 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
2693 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 Py_DECREF(bytes);
2695 }
2696
2697 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002698 *psize = PyUnicode_UTF8_LENGTH(unicode);
2699 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002700}
2701
2702char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002704{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002705 return PyUnicode_AsUTF8AndSize(unicode, NULL);
2706}
2707
2708#ifdef Py_DEBUG
2709int unicode_as_unicode_calls = 0;
2710#endif
2711
2712
2713Py_UNICODE *
2714PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
2715{
2716 PyUnicodeObject *u;
2717 const unsigned char *one_byte;
2718#if SIZEOF_WCHAR_T == 4
2719 const Py_UCS2 *two_bytes;
2720#else
2721 const Py_UCS4 *four_bytes;
2722 const Py_UCS4 *ucs4_end;
2723 Py_ssize_t num_surrogates;
2724#endif
2725 wchar_t *w;
2726 wchar_t *wchar_end;
2727
2728 if (!PyUnicode_Check(unicode)) {
2729 PyErr_BadArgument();
2730 return NULL;
2731 }
2732 u = (PyUnicodeObject*)unicode;
2733 if (_PyUnicode_WSTR(u) == NULL) {
2734 /* Non-ASCII compact unicode object */
2735 assert(_PyUnicode_KIND(u) != 0);
2736 assert(PyUnicode_IS_READY(u));
2737
2738#ifdef Py_DEBUG
2739 ++unicode_as_unicode_calls;
2740#endif
2741
2742 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
2743#if SIZEOF_WCHAR_T == 2
2744 four_bytes = PyUnicode_4BYTE_DATA(u);
2745 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
2746 num_surrogates = 0;
2747
2748 for (; four_bytes < ucs4_end; ++four_bytes) {
2749 if (*four_bytes > 0xFFFF)
2750 ++num_surrogates;
2751 }
2752
2753 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
2754 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
2755 if (!_PyUnicode_WSTR(u)) {
2756 PyErr_NoMemory();
2757 return NULL;
2758 }
2759 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
2760
2761 w = _PyUnicode_WSTR(u);
2762 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
2763 four_bytes = PyUnicode_4BYTE_DATA(u);
2764 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
2765 if (*four_bytes > 0xFFFF) {
2766 /* encode surrogate pair in this case */
2767 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
2768 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
2769 }
2770 else
2771 *w = *four_bytes;
2772
2773 if (w > wchar_end) {
2774 assert(0 && "Miscalculated string end");
2775 }
2776 }
2777 *w = 0;
2778#else
2779 /* sizeof(wchar_t) == 4 */
2780 Py_FatalError("Impossible unicode object state, wstr and str "
2781 "should share memory already.");
2782 return NULL;
2783#endif
2784 }
2785 else {
2786 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
2787 (_PyUnicode_LENGTH(u) + 1));
2788 if (!_PyUnicode_WSTR(u)) {
2789 PyErr_NoMemory();
2790 return NULL;
2791 }
2792 if (!PyUnicode_IS_COMPACT_ASCII(u))
2793 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
2794 w = _PyUnicode_WSTR(u);
2795 wchar_end = w + _PyUnicode_LENGTH(u);
2796
2797 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
2798 one_byte = PyUnicode_1BYTE_DATA(u);
2799 for (; w < wchar_end; ++one_byte, ++w)
2800 *w = *one_byte;
2801 /* null-terminate the wstr */
2802 *w = 0;
2803 }
2804 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
2805#if SIZEOF_WCHAR_T == 4
2806 two_bytes = PyUnicode_2BYTE_DATA(u);
2807 for (; w < wchar_end; ++two_bytes, ++w)
2808 *w = *two_bytes;
2809 /* null-terminate the wstr */
2810 *w = 0;
2811#else
2812 /* sizeof(wchar_t) == 2 */
2813 PyObject_FREE(_PyUnicode_WSTR(u));
2814 _PyUnicode_WSTR(u) = NULL;
2815 Py_FatalError("Impossible unicode object state, wstr "
2816 "and str should share memory already.");
2817 return NULL;
2818#endif
2819 }
2820 else {
2821 assert(0 && "This should never happen.");
2822 }
2823 }
2824 }
2825 if (size != NULL)
2826 *size = PyUnicode_WSTR_LENGTH(u);
2827 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002828}
2829
Alexander Belopolsky40018472011-02-26 01:02:56 +00002830Py_UNICODE *
2831PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002834}
2835
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836
Alexander Belopolsky40018472011-02-26 01:02:56 +00002837Py_ssize_t
2838PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002839{
2840 if (!PyUnicode_Check(unicode)) {
2841 PyErr_BadArgument();
2842 goto onError;
2843 }
2844 return PyUnicode_GET_SIZE(unicode);
2845
Benjamin Peterson29060642009-01-31 22:14:21 +00002846 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002847 return -1;
2848}
2849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850Py_ssize_t
2851PyUnicode_GetLength(PyObject *unicode)
2852{
Victor Stinner5a706cf2011-10-02 00:36:53 +02002853 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002854 PyErr_BadArgument();
2855 return -1;
2856 }
2857
2858 return PyUnicode_GET_LENGTH(unicode);
2859}
2860
2861Py_UCS4
2862PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
2863{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02002864 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
2865 PyErr_BadArgument();
2866 return (Py_UCS4)-1;
2867 }
2868 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
2869 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 return (Py_UCS4)-1;
2871 }
2872 return PyUnicode_READ_CHAR(unicode, index);
2873}
2874
2875int
2876PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
2877{
2878 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02002879 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002880 return -1;
2881 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02002882 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
2883 PyErr_SetString(PyExc_IndexError, "string index out of range");
2884 return -1;
2885 }
2886 if (_PyUnicode_Dirty(unicode))
2887 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002888 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
2889 index, ch);
2890 return 0;
2891}
2892
Alexander Belopolsky40018472011-02-26 01:02:56 +00002893const char *
2894PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00002895{
Victor Stinner42cb4622010-09-01 19:39:01 +00002896 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00002897}
2898
Victor Stinner554f3f02010-06-16 23:33:54 +00002899/* create or adjust a UnicodeDecodeError */
2900static void
2901make_decode_exception(PyObject **exceptionObject,
2902 const char *encoding,
2903 const char *input, Py_ssize_t length,
2904 Py_ssize_t startpos, Py_ssize_t endpos,
2905 const char *reason)
2906{
2907 if (*exceptionObject == NULL) {
2908 *exceptionObject = PyUnicodeDecodeError_Create(
2909 encoding, input, length, startpos, endpos, reason);
2910 }
2911 else {
2912 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
2913 goto onError;
2914 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
2915 goto onError;
2916 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
2917 goto onError;
2918 }
2919 return;
2920
2921onError:
2922 Py_DECREF(*exceptionObject);
2923 *exceptionObject = NULL;
2924}
2925
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002926/* error handling callback helper:
2927 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00002928 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002929 and adjust various state variables.
2930 return 0 on success, -1 on error
2931*/
2932
Alexander Belopolsky40018472011-02-26 01:02:56 +00002933static int
2934unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002935 const char *encoding, const char *reason,
2936 const char **input, const char **inend, Py_ssize_t *startinpos,
2937 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
2938 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002939{
Benjamin Peterson142957c2008-07-04 19:55:29 +00002940 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002941
2942 PyObject *restuple = NULL;
2943 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002944 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002945 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002946 Py_ssize_t requiredsize;
2947 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002948 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002949 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002950 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002951 int res = -1;
2952
2953 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002954 *errorHandler = PyCodec_LookupError(errors);
2955 if (*errorHandler == NULL)
2956 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002957 }
2958
Victor Stinner554f3f02010-06-16 23:33:54 +00002959 make_decode_exception(exceptionObject,
2960 encoding,
2961 *input, *inend - *input,
2962 *startinpos, *endinpos,
2963 reason);
2964 if (*exceptionObject == NULL)
2965 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002966
2967 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
2968 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002969 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002970 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00002971 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002973 }
2974 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00002975 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00002976
2977 /* Copy back the bytes variables, which might have been modified by the
2978 callback */
2979 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
2980 if (!inputobj)
2981 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00002982 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002983 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00002984 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002985 *input = PyBytes_AS_STRING(inputobj);
2986 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002987 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00002988 /* we can DECREF safely, as the exception has another reference,
2989 so the object won't go away. */
2990 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00002991
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002992 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00002993 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002994 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002995 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
2996 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00002997 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002998
2999 /* need more space? (at least enough for what we
3000 have+the replacement+the rest of the string (starting
3001 at the new input position), so we won't have to check space
3002 when there are no errors in the rest of the string) */
3003 repptr = PyUnicode_AS_UNICODE(repunicode);
3004 repsize = PyUnicode_GET_SIZE(repunicode);
3005 requiredsize = *outpos + repsize + insize-newpos;
3006 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 if (requiredsize<2*outsize)
3008 requiredsize = 2*outsize;
3009 if (_PyUnicode_Resize(output, requiredsize) < 0)
3010 goto onError;
3011 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003012 }
3013 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003014 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003015 Py_UNICODE_COPY(*outptr, repptr, repsize);
3016 *outptr += repsize;
3017 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003018
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003019 /* we made it! */
3020 res = 0;
3021
Benjamin Peterson29060642009-01-31 22:14:21 +00003022 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003023 Py_XDECREF(restuple);
3024 return res;
3025}
3026
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003027/* --- UTF-7 Codec -------------------------------------------------------- */
3028
Antoine Pitrou244651a2009-05-04 18:56:13 +00003029/* See RFC2152 for details. We encode conservatively and decode liberally. */
3030
3031/* Three simple macros defining base-64. */
3032
3033/* Is c a base-64 character? */
3034
3035#define IS_BASE64(c) \
3036 (((c) >= 'A' && (c) <= 'Z') || \
3037 ((c) >= 'a' && (c) <= 'z') || \
3038 ((c) >= '0' && (c) <= '9') || \
3039 (c) == '+' || (c) == '/')
3040
3041/* given that c is a base-64 character, what is its base-64 value? */
3042
3043#define FROM_BASE64(c) \
3044 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3045 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3046 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3047 (c) == '+' ? 62 : 63)
3048
3049/* What is the base-64 character of the bottom 6 bits of n? */
3050
3051#define TO_BASE64(n) \
3052 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3053
3054/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3055 * decoded as itself. We are permissive on decoding; the only ASCII
3056 * byte not decoding to itself is the + which begins a base64
3057 * string. */
3058
3059#define DECODE_DIRECT(c) \
3060 ((c) <= 127 && (c) != '+')
3061
3062/* The UTF-7 encoder treats ASCII characters differently according to
3063 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3064 * the above). See RFC2152. This array identifies these different
3065 * sets:
3066 * 0 : "Set D"
3067 * alphanumeric and '(),-./:?
3068 * 1 : "Set O"
3069 * !"#$%&*;<=>@[]^_`{|}
3070 * 2 : "whitespace"
3071 * ht nl cr sp
3072 * 3 : special (must be base64 encoded)
3073 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3074 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003075
Tim Petersced69f82003-09-16 20:30:58 +00003076static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003077char utf7_category[128] = {
3078/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3079 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3080/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3081 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3082/* sp ! " # $ % & ' ( ) * + , - . / */
3083 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3084/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3085 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3086/* @ A B C D E F G H I J K L M N O */
3087 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3088/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3090/* ` a b c d e f g h i j k l m n o */
3091 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3092/* p q r s t u v w x y z { | } ~ del */
3093 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003094};
3095
Antoine Pitrou244651a2009-05-04 18:56:13 +00003096/* ENCODE_DIRECT: this character should be encoded as itself. The
3097 * answer depends on whether we are encoding set O as itself, and also
3098 * on whether we are encoding whitespace as itself. RFC2152 makes it
3099 * clear that the answers to these questions vary between
3100 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003101
Antoine Pitrou244651a2009-05-04 18:56:13 +00003102#define ENCODE_DIRECT(c, directO, directWS) \
3103 ((c) < 128 && (c) > 0 && \
3104 ((utf7_category[(c)] == 0) || \
3105 (directWS && (utf7_category[(c)] == 2)) || \
3106 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003107
Alexander Belopolsky40018472011-02-26 01:02:56 +00003108PyObject *
3109PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003110 Py_ssize_t size,
3111 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003112{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003113 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3114}
3115
Antoine Pitrou244651a2009-05-04 18:56:13 +00003116/* The decoder. The only state we preserve is our read position,
3117 * i.e. how many characters we have consumed. So if we end in the
3118 * middle of a shift sequence we have to back off the read position
3119 * and the output to the beginning of the sequence, otherwise we lose
3120 * all the shift state (seen bits, number of bits seen, high
3121 * surrogate). */
3122
Alexander Belopolsky40018472011-02-26 01:02:56 +00003123PyObject *
3124PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003125 Py_ssize_t size,
3126 const char *errors,
3127 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003128{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003129 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003130 Py_ssize_t startinpos;
3131 Py_ssize_t endinpos;
3132 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003133 const char *e;
3134 PyUnicodeObject *unicode;
3135 Py_UNICODE *p;
3136 const char *errmsg = "";
3137 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003138 Py_UNICODE *shiftOutStart;
3139 unsigned int base64bits = 0;
3140 unsigned long base64buffer = 0;
3141 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003142 PyObject *errorHandler = NULL;
3143 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003144
3145 unicode = _PyUnicode_New(size);
3146 if (!unicode)
3147 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003148 if (size == 0) {
3149 if (consumed)
3150 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003151 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003152 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003155 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003156 e = s + size;
3157
3158 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003159 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003160 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003161 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003162
Antoine Pitrou244651a2009-05-04 18:56:13 +00003163 if (inShift) { /* in a base-64 section */
3164 if (IS_BASE64(ch)) { /* consume a base-64 character */
3165 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3166 base64bits += 6;
3167 s++;
3168 if (base64bits >= 16) {
3169 /* we have enough bits for a UTF-16 value */
3170 Py_UNICODE outCh = (Py_UNICODE)
3171 (base64buffer >> (base64bits-16));
3172 base64bits -= 16;
3173 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3174 if (surrogate) {
3175 /* expecting a second surrogate */
3176 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3177#ifdef Py_UNICODE_WIDE
3178 *p++ = (((surrogate & 0x3FF)<<10)
3179 | (outCh & 0x3FF)) + 0x10000;
3180#else
3181 *p++ = surrogate;
3182 *p++ = outCh;
3183#endif
3184 surrogate = 0;
3185 }
3186 else {
3187 surrogate = 0;
3188 errmsg = "second surrogate missing";
3189 goto utf7Error;
3190 }
3191 }
3192 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3193 /* first surrogate */
3194 surrogate = outCh;
3195 }
3196 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3197 errmsg = "unexpected second surrogate";
3198 goto utf7Error;
3199 }
3200 else {
3201 *p++ = outCh;
3202 }
3203 }
3204 }
3205 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003206 inShift = 0;
3207 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003208 if (surrogate) {
3209 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003210 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003211 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003212 if (base64bits > 0) { /* left-over bits */
3213 if (base64bits >= 6) {
3214 /* We've seen at least one base-64 character */
3215 errmsg = "partial character in shift sequence";
3216 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003217 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003218 else {
3219 /* Some bits remain; they should be zero */
3220 if (base64buffer != 0) {
3221 errmsg = "non-zero padding bits in shift sequence";
3222 goto utf7Error;
3223 }
3224 }
3225 }
3226 if (ch != '-') {
3227 /* '-' is absorbed; other terminating
3228 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003229 *p++ = ch;
3230 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003231 }
3232 }
3233 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003234 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003235 s++; /* consume '+' */
3236 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003237 s++;
3238 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003239 }
3240 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003241 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003242 shiftOutStart = p;
3243 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003244 }
3245 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003246 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003247 *p++ = ch;
3248 s++;
3249 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003250 else {
3251 startinpos = s-starts;
3252 s++;
3253 errmsg = "unexpected special character";
3254 goto utf7Error;
3255 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003256 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003257utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003258 outpos = p-PyUnicode_AS_UNICODE(unicode);
3259 endinpos = s-starts;
3260 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003261 errors, &errorHandler,
3262 "utf7", errmsg,
3263 &starts, &e, &startinpos, &endinpos, &exc, &s,
3264 &unicode, &outpos, &p))
3265 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003266 }
3267
Antoine Pitrou244651a2009-05-04 18:56:13 +00003268 /* end of string */
3269
3270 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3271 /* if we're in an inconsistent state, that's an error */
3272 if (surrogate ||
3273 (base64bits >= 6) ||
3274 (base64bits > 0 && base64buffer != 0)) {
3275 outpos = p-PyUnicode_AS_UNICODE(unicode);
3276 endinpos = size;
3277 if (unicode_decode_call_errorhandler(
3278 errors, &errorHandler,
3279 "utf7", "unterminated shift sequence",
3280 &starts, &e, &startinpos, &endinpos, &exc, &s,
3281 &unicode, &outpos, &p))
3282 goto onError;
3283 if (s < e)
3284 goto restart;
3285 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003286 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003287
3288 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003289 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003290 if (inShift) {
3291 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003292 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003293 }
3294 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003295 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003296 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003297 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003298
Jeremy Hyltondeb2dc62003-09-16 03:41:45 +00003299 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003300 goto onError;
3301
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003302 Py_XDECREF(errorHandler);
3303 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003304 if (PyUnicode_READY(unicode) == -1) {
3305 Py_DECREF(unicode);
3306 return NULL;
3307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003308 return (PyObject *)unicode;
3309
Benjamin Peterson29060642009-01-31 22:14:21 +00003310 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003311 Py_XDECREF(errorHandler);
3312 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003313 Py_DECREF(unicode);
3314 return NULL;
3315}
3316
3317
Alexander Belopolsky40018472011-02-26 01:02:56 +00003318PyObject *
3319PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003320 Py_ssize_t size,
3321 int base64SetO,
3322 int base64WhiteSpace,
3323 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003324{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003325 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003326 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003327 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003328 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003329 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003330 unsigned int base64bits = 0;
3331 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003332 char * out;
3333 char * start;
3334
3335 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003336 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003337
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003338 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003339 return PyErr_NoMemory();
3340
Antoine Pitrou244651a2009-05-04 18:56:13 +00003341 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003342 if (v == NULL)
3343 return NULL;
3344
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003345 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003346 for (;i < size; ++i) {
3347 Py_UNICODE ch = s[i];
3348
Antoine Pitrou244651a2009-05-04 18:56:13 +00003349 if (inShift) {
3350 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3351 /* shifting out */
3352 if (base64bits) { /* output remaining bits */
3353 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3354 base64buffer = 0;
3355 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003356 }
3357 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003358 /* Characters not in the BASE64 set implicitly unshift the sequence
3359 so no '-' is required, except if the character is itself a '-' */
3360 if (IS_BASE64(ch) || ch == '-') {
3361 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003362 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003363 *out++ = (char) ch;
3364 }
3365 else {
3366 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003367 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003368 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003369 else { /* not in a shift sequence */
3370 if (ch == '+') {
3371 *out++ = '+';
3372 *out++ = '-';
3373 }
3374 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3375 *out++ = (char) ch;
3376 }
3377 else {
3378 *out++ = '+';
3379 inShift = 1;
3380 goto encode_char;
3381 }
3382 }
3383 continue;
3384encode_char:
3385#ifdef Py_UNICODE_WIDE
3386 if (ch >= 0x10000) {
3387 /* code first surrogate */
3388 base64bits += 16;
3389 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3390 while (base64bits >= 6) {
3391 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3392 base64bits -= 6;
3393 }
3394 /* prepare second surrogate */
3395 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3396 }
3397#endif
3398 base64bits += 16;
3399 base64buffer = (base64buffer << 16) | ch;
3400 while (base64bits >= 6) {
3401 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3402 base64bits -= 6;
3403 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003404 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003405 if (base64bits)
3406 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3407 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003408 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003409 if (_PyBytes_Resize(&v, out - start) < 0)
3410 return NULL;
3411 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003412}
3413
Antoine Pitrou244651a2009-05-04 18:56:13 +00003414#undef IS_BASE64
3415#undef FROM_BASE64
3416#undef TO_BASE64
3417#undef DECODE_DIRECT
3418#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003419
Guido van Rossumd57fd912000-03-10 22:53:23 +00003420/* --- UTF-8 Codec -------------------------------------------------------- */
3421
Tim Petersced69f82003-09-16 20:30:58 +00003422static
Guido van Rossumd57fd912000-03-10 22:53:23 +00003423char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00003424 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
3425 illegal prefix. See RFC 3629 for details */
3426 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
3427 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003428 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3430 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3431 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3432 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00003433 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
3434 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 +00003435 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3436 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00003437 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
3438 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
3439 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
3440 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
3441 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 +00003442};
3443
Alexander Belopolsky40018472011-02-26 01:02:56 +00003444PyObject *
3445PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003446 Py_ssize_t size,
3447 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003448{
Walter Dörwald69652032004-09-07 20:24:22 +00003449 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3450}
3451
Antoine Pitrouab868312009-01-10 15:40:25 +00003452/* Mask to check or force alignment of a pointer to C 'long' boundaries */
3453#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
3454
3455/* Mask to quickly check whether a C 'long' contains a
3456 non-ASCII, UTF8-encoded char. */
3457#if (SIZEOF_LONG == 8)
3458# define ASCII_CHAR_MASK 0x8080808080808080L
3459#elif (SIZEOF_LONG == 4)
3460# define ASCII_CHAR_MASK 0x80808080L
3461#else
3462# error C 'long' size should be either 4 or 8!
3463#endif
3464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465/* Scans a UTF-8 string and returns the maximum character to be expected,
3466 the size of the decoded unicode string and if any major errors were
3467 encountered.
3468
3469 This function does check basic UTF-8 sanity, it does however NOT CHECK
3470 if the string contains surrogates, and if all continuation bytes are
3471 within the correct ranges, these checks are performed in
3472 PyUnicode_DecodeUTF8Stateful.
3473
3474 If it sets has_errors to 1, it means the value of unicode_size and max_char
3475 will be bogus and you should not rely on useful information in them.
3476 */
3477static Py_UCS4
3478utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
3479 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
3480 int *has_errors)
3481{
3482 Py_ssize_t n;
3483 Py_ssize_t char_count = 0;
3484 Py_UCS4 max_char = 127, new_max;
3485 Py_UCS4 upper_bound;
3486 const unsigned char *p = (const unsigned char *)s;
3487 const unsigned char *end = p + string_size;
3488 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
3489 int err = 0;
3490
3491 for (; p < end && !err; ++p, ++char_count) {
3492 /* Only check value if it's not a ASCII char... */
3493 if (*p < 0x80) {
3494 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
3495 an explanation. */
3496 if (!((size_t) p & LONG_PTR_MASK)) {
3497 /* Help register allocation */
3498 register const unsigned char *_p = p;
3499 while (_p < aligned_end) {
3500 unsigned long value = *(unsigned long *) _p;
3501 if (value & ASCII_CHAR_MASK)
3502 break;
3503 _p += SIZEOF_LONG;
3504 char_count += SIZEOF_LONG;
3505 }
3506 p = _p;
3507 if (p == end)
3508 break;
3509 }
3510 }
3511 if (*p >= 0x80) {
3512 n = utf8_code_length[*p];
3513 new_max = max_char;
3514 switch (n) {
3515 /* invalid start byte */
3516 case 0:
3517 err = 1;
3518 break;
3519 case 2:
3520 /* Code points between 0x00FF and 0x07FF inclusive.
3521 Approximate the upper bound of the code point,
3522 if this flips over 255 we can be sure it will be more
3523 than 255 and the string will need 2 bytes per code coint,
3524 if it stays under or equal to 255, we can be sure 1 byte
3525 is enough.
3526 ((*p & 0b00011111) << 6) | 0b00111111 */
3527 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
3528 if (max_char < upper_bound)
3529 new_max = upper_bound;
3530 /* Ensure we track at least that we left ASCII space. */
3531 if (new_max < 128)
3532 new_max = 128;
3533 break;
3534 case 3:
3535 /* Between 0x0FFF and 0xFFFF inclusive, so values are
3536 always > 255 and <= 65535 and will always need 2 bytes. */
3537 if (max_char < 65535)
3538 new_max = 65535;
3539 break;
3540 case 4:
3541 /* Code point will be above 0xFFFF for sure in this case. */
3542 new_max = 65537;
3543 break;
3544 /* Internal error, this should be caught by the first if */
3545 case 1:
3546 default:
3547 assert(0 && "Impossible case in utf8_max_char_and_size");
3548 err = 1;
3549 }
3550 /* Instead of number of overall bytes for this code point,
3551 n containts the number of following bytes: */
3552 --n;
3553 /* Check if the follow up chars are all valid continuation bytes */
3554 if (n >= 1) {
3555 const unsigned char *cont;
3556 if ((p + n) >= end) {
3557 if (consumed == 0)
3558 /* incomplete data, non-incremental decoding */
3559 err = 1;
3560 break;
3561 }
3562 for (cont = p + 1; cont < (p + n); ++cont) {
3563 if ((*cont & 0xc0) != 0x80) {
3564 err = 1;
3565 break;
3566 }
3567 }
3568 p += n;
3569 }
3570 else
3571 err = 1;
3572 max_char = new_max;
3573 }
3574 }
3575
3576 if (unicode_size)
3577 *unicode_size = char_count;
3578 if (has_errors)
3579 *has_errors = err;
3580 return max_char;
3581}
3582
3583/* Similar to PyUnicode_WRITE but can also write into wstr field
3584 of the legacy unicode representation */
3585#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
3586 do { \
3587 const int k_ = (kind); \
3588 if (k_ == PyUnicode_WCHAR_KIND) \
3589 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
3590 else if (k_ == PyUnicode_1BYTE_KIND) \
3591 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
3592 else if (k_ == PyUnicode_2BYTE_KIND) \
3593 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
3594 else \
3595 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
3596 } while (0)
3597
Alexander Belopolsky40018472011-02-26 01:02:56 +00003598PyObject *
3599PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003600 Py_ssize_t size,
3601 const char *errors,
3602 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003603{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003604 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003605 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00003606 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003607 Py_ssize_t startinpos;
3608 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00003609 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003610 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003611 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003612 PyObject *errorHandler = NULL;
3613 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003614 Py_UCS4 maxchar = 0;
3615 Py_ssize_t unicode_size;
3616 Py_ssize_t i;
3617 int kind;
3618 void *data;
3619 int has_errors;
3620 Py_UNICODE *error_outptr;
3621#if SIZEOF_WCHAR_T == 2
3622 Py_ssize_t wchar_offset = 0;
3623#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003624
Walter Dörwald69652032004-09-07 20:24:22 +00003625 if (size == 0) {
3626 if (consumed)
3627 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003628 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00003629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003630 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
3631 consumed, &has_errors);
3632 if (has_errors) {
3633 unicode = _PyUnicode_New(size);
3634 if (!unicode)
3635 return NULL;
3636 kind = PyUnicode_WCHAR_KIND;
3637 data = PyUnicode_AS_UNICODE(unicode);
3638 assert(data != NULL);
3639 }
3640 else {
3641 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
3642 if (!unicode)
3643 return NULL;
3644 /* When the string is ASCII only, just use memcpy and return.
3645 unicode_size may be != size if there is an incomplete UTF-8
3646 sequence at the end of the ASCII block. */
3647 if (maxchar < 128 && size == unicode_size) {
3648 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
3649 return (PyObject *)unicode;
3650 }
3651 kind = PyUnicode_KIND(unicode);
3652 data = PyUnicode_DATA(unicode);
3653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003654 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003655 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003656 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00003657 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003658
3659 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003660 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003661
3662 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00003663 /* Fast path for runs of ASCII characters. Given that common UTF-8
3664 input will consist of an overwhelming majority of ASCII
3665 characters, we try to optimize for this case by checking
3666 as many characters as a C 'long' can contain.
3667 First, check if we can do an aligned read, as most CPUs have
3668 a penalty for unaligned reads.
3669 */
3670 if (!((size_t) s & LONG_PTR_MASK)) {
3671 /* Help register allocation */
3672 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003673 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003674 while (_s < aligned_end) {
3675 /* Read a whole long at a time (either 4 or 8 bytes),
3676 and do a fast unrolled copy if it only contains ASCII
3677 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003678 unsigned long value = *(unsigned long *) _s;
3679 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00003680 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003681 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
3682 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
3683 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
3684 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003685#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003686 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
3687 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
3688 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
3689 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003690#endif
3691 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003692 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00003693 }
3694 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003696 if (s == e)
3697 break;
3698 ch = (unsigned char)*s;
3699 }
3700 }
3701
3702 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003703 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003704 s++;
3705 continue;
3706 }
3707
3708 n = utf8_code_length[ch];
3709
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003710 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003711 if (consumed)
3712 break;
3713 else {
3714 errmsg = "unexpected end of data";
3715 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003716 endinpos = startinpos+1;
3717 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
3718 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003719 goto utf8Error;
3720 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003721 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003722
3723 switch (n) {
3724
3725 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00003726 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003727 startinpos = s-starts;
3728 endinpos = startinpos+1;
3729 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003730
3731 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003732 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00003733 startinpos = s-starts;
3734 endinpos = startinpos+1;
3735 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003736
3737 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003738 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00003739 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003740 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003741 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00003742 goto utf8Error;
3743 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003744 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003745 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003746 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003747 break;
3748
3749 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00003750 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
3751 will result in surrogates in range d800-dfff. Surrogates are
3752 not valid UTF-8 so they are rejected.
3753 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
3754 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00003755 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003756 (s[2] & 0xc0) != 0x80 ||
3757 ((unsigned char)s[0] == 0xE0 &&
3758 (unsigned char)s[1] < 0xA0) ||
3759 ((unsigned char)s[0] == 0xED &&
3760 (unsigned char)s[1] > 0x9F)) {
3761 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003762 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003763 endinpos = startinpos + 1;
3764
3765 /* if s[1] first two bits are 1 and 0, then the invalid
3766 continuation byte is s[2], so increment endinpos by 1,
3767 if not, s[1] is invalid and endinpos doesn't need to
3768 be incremented. */
3769 if ((s[1] & 0xC0) == 0x80)
3770 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003771 goto utf8Error;
3772 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003773 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003774 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003775 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003776 break;
3777
3778 case 4:
3779 if ((s[1] & 0xc0) != 0x80 ||
3780 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003781 (s[3] & 0xc0) != 0x80 ||
3782 ((unsigned char)s[0] == 0xF0 &&
3783 (unsigned char)s[1] < 0x90) ||
3784 ((unsigned char)s[0] == 0xF4 &&
3785 (unsigned char)s[1] > 0x8F)) {
3786 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003787 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003788 endinpos = startinpos + 1;
3789 if ((s[1] & 0xC0) == 0x80) {
3790 endinpos++;
3791 if ((s[2] & 0xC0) == 0x80)
3792 endinpos++;
3793 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003794 goto utf8Error;
3795 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003796 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00003797 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
3798 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
3799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003800 /* If the string is flexible or we have native UCS-4, write
3801 directly.. */
3802 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
3803 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00003804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 else {
3806 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00003807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003808 /* translate from 10000..10FFFF to 0..FFFF */
3809 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00003810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 /* high surrogate = top 10 bits added to D800 */
3812 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
3813 (Py_UNICODE)(0xD800 + (ch >> 10)));
3814
3815 /* low surrogate = bottom 10 bits added to DC00 */
3816 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
3817 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
3818 }
3819#if SIZEOF_WCHAR_T == 2
3820 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00003821#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003822 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003823 }
3824 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00003825 continue;
Tim Petersced69f82003-09-16 20:30:58 +00003826
Benjamin Peterson29060642009-01-31 22:14:21 +00003827 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003828 /* If this is not yet a resizable string, make it one.. */
3829 if (kind != PyUnicode_WCHAR_KIND) {
3830 const Py_UNICODE *u;
3831 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
3832 if (!new_unicode)
3833 goto onError;
3834 u = PyUnicode_AsUnicode((PyObject *)unicode);
3835 if (!u)
3836 goto onError;
3837#if SIZEOF_WCHAR_T == 2
3838 i += wchar_offset;
3839#endif
3840 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
3841 Py_DECREF(unicode);
3842 unicode = new_unicode;
3843 kind = 0;
3844 data = PyUnicode_AS_UNICODE(new_unicode);
3845 assert(data != NULL);
3846 }
3847 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00003848 if (unicode_decode_call_errorhandler(
3849 errors, &errorHandler,
3850 "utf8", errmsg,
3851 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003852 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00003853 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003854 /* Update data because unicode_decode_call_errorhandler might have
3855 re-created or resized the unicode object. */
3856 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00003857 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 /* Ensure the unicode_size calculation above was correct: */
3860 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
3861
Walter Dörwald69652032004-09-07 20:24:22 +00003862 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00003863 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 /* Adjust length and ready string when it contained errors and
3866 is of the old resizable kind. */
3867 if (kind == PyUnicode_WCHAR_KIND) {
3868 if (_PyUnicode_Resize(&unicode, i) < 0 ||
3869 PyUnicode_READY(unicode) == -1)
3870 goto onError;
3871 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003872
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003873 Py_XDECREF(errorHandler);
3874 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 if (PyUnicode_READY(unicode) == -1) {
3876 Py_DECREF(unicode);
3877 return NULL;
3878 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003879 return (PyObject *)unicode;
3880
Benjamin Peterson29060642009-01-31 22:14:21 +00003881 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003882 Py_XDECREF(errorHandler);
3883 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003884 Py_DECREF(unicode);
3885 return NULL;
3886}
3887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00003889
Victor Stinnerf933e1a2010-10-20 22:58:25 +00003890#ifdef __APPLE__
3891
3892/* Simplified UTF-8 decoder using surrogateescape error handler,
3893 used to decode the command line arguments on Mac OS X. */
3894
3895wchar_t*
3896_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
3897{
3898 int n;
3899 const char *e;
3900 wchar_t *unicode, *p;
3901
3902 /* Note: size will always be longer than the resulting Unicode
3903 character count */
3904 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
3905 PyErr_NoMemory();
3906 return NULL;
3907 }
3908 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
3909 if (!unicode)
3910 return NULL;
3911
3912 /* Unpack UTF-8 encoded data */
3913 p = unicode;
3914 e = s + size;
3915 while (s < e) {
3916 Py_UCS4 ch = (unsigned char)*s;
3917
3918 if (ch < 0x80) {
3919 *p++ = (wchar_t)ch;
3920 s++;
3921 continue;
3922 }
3923
3924 n = utf8_code_length[ch];
3925 if (s + n > e) {
3926 goto surrogateescape;
3927 }
3928
3929 switch (n) {
3930 case 0:
3931 case 1:
3932 goto surrogateescape;
3933
3934 case 2:
3935 if ((s[1] & 0xc0) != 0x80)
3936 goto surrogateescape;
3937 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
3938 assert ((ch > 0x007F) && (ch <= 0x07FF));
3939 *p++ = (wchar_t)ch;
3940 break;
3941
3942 case 3:
3943 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
3944 will result in surrogates in range d800-dfff. Surrogates are
3945 not valid UTF-8 so they are rejected.
3946 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
3947 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
3948 if ((s[1] & 0xc0) != 0x80 ||
3949 (s[2] & 0xc0) != 0x80 ||
3950 ((unsigned char)s[0] == 0xE0 &&
3951 (unsigned char)s[1] < 0xA0) ||
3952 ((unsigned char)s[0] == 0xED &&
3953 (unsigned char)s[1] > 0x9F)) {
3954
3955 goto surrogateescape;
3956 }
3957 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
3958 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003959 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00003960 break;
3961
3962 case 4:
3963 if ((s[1] & 0xc0) != 0x80 ||
3964 (s[2] & 0xc0) != 0x80 ||
3965 (s[3] & 0xc0) != 0x80 ||
3966 ((unsigned char)s[0] == 0xF0 &&
3967 (unsigned char)s[1] < 0x90) ||
3968 ((unsigned char)s[0] == 0xF4 &&
3969 (unsigned char)s[1] > 0x8F)) {
3970 goto surrogateescape;
3971 }
3972 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
3973 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
3974 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
3975
3976#if SIZEOF_WCHAR_T == 4
3977 *p++ = (wchar_t)ch;
3978#else
3979 /* compute and append the two surrogates: */
3980
3981 /* translate from 10000..10FFFF to 0..FFFF */
3982 ch -= 0x10000;
3983
3984 /* high surrogate = top 10 bits added to D800 */
3985 *p++ = (wchar_t)(0xD800 + (ch >> 10));
3986
3987 /* low surrogate = bottom 10 bits added to DC00 */
3988 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
3989#endif
3990 break;
3991 }
3992 s += n;
3993 continue;
3994
3995 surrogateescape:
3996 *p++ = 0xDC00 + ch;
3997 s++;
3998 }
3999 *p = L'\0';
4000 return unicode;
4001}
4002
4003#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004005/* Primary internal function which creates utf8 encoded bytes objects.
4006
4007 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004008 and allocate exactly as much space needed at the end. Else allocate the
4009 maximum possible needed (4 result bytes per Unicode character), and return
4010 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004011*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004012PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004013_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004014{
Tim Peters602f7402002-04-27 18:03:26 +00004015#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004016
Guido van Rossum98297ee2007-11-06 21:34:58 +00004017 Py_ssize_t i; /* index into s of next input byte */
4018 PyObject *result; /* result string object */
4019 char *p; /* next free byte in output buffer */
4020 Py_ssize_t nallocated; /* number of result bytes allocated */
4021 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004022 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004023 PyObject *errorHandler = NULL;
4024 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004025 int kind;
4026 void *data;
4027 Py_ssize_t size;
4028 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4029#if SIZEOF_WCHAR_T == 2
4030 Py_ssize_t wchar_offset = 0;
4031#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004033 if (!PyUnicode_Check(unicode)) {
4034 PyErr_BadArgument();
4035 return NULL;
4036 }
4037
4038 if (PyUnicode_READY(unicode) == -1)
4039 return NULL;
4040
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004041 if (PyUnicode_UTF8(unicode))
4042 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4043 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004044
4045 kind = PyUnicode_KIND(unicode);
4046 data = PyUnicode_DATA(unicode);
4047 size = PyUnicode_GET_LENGTH(unicode);
4048
Tim Peters602f7402002-04-27 18:03:26 +00004049 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004050
Tim Peters602f7402002-04-27 18:03:26 +00004051 if (size <= MAX_SHORT_UNICHARS) {
4052 /* Write into the stack buffer; nallocated can't overflow.
4053 * At the end, we'll allocate exactly as much heap space as it
4054 * turns out we need.
4055 */
4056 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004057 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004058 p = stackbuf;
4059 }
4060 else {
4061 /* Overallocate on the heap, and give the excess back at the end. */
4062 nallocated = size * 4;
4063 if (nallocated / 4 != size) /* overflow! */
4064 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004065 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004066 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004067 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004068 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004069 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004070
Tim Peters602f7402002-04-27 18:03:26 +00004071 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004072 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004073
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004074 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004075 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004076 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004077
Guido van Rossumd57fd912000-03-10 22:53:23 +00004078 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004079 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004080 *p++ = (char)(0xc0 | (ch >> 6));
4081 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004082 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004083 Py_ssize_t newpos;
4084 PyObject *rep;
4085 Py_ssize_t repsize, k, startpos;
4086 startpos = i-1;
4087#if SIZEOF_WCHAR_T == 2
4088 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004089#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004090 rep = unicode_encode_call_errorhandler(
4091 errors, &errorHandler, "utf-8", "surrogates not allowed",
4092 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4093 &exc, startpos, startpos+1, &newpos);
4094 if (!rep)
4095 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097 if (PyBytes_Check(rep))
4098 repsize = PyBytes_GET_SIZE(rep);
4099 else
4100 repsize = PyUnicode_GET_SIZE(rep);
4101
4102 if (repsize > 4) {
4103 Py_ssize_t offset;
4104
4105 if (result == NULL)
4106 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004107 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004108 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004110 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4111 /* integer overflow */
4112 PyErr_NoMemory();
4113 goto error;
4114 }
4115 nallocated += repsize - 4;
4116 if (result != NULL) {
4117 if (_PyBytes_Resize(&result, nallocated) < 0)
4118 goto error;
4119 } else {
4120 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004121 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004122 goto error;
4123 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4124 }
4125 p = PyBytes_AS_STRING(result) + offset;
4126 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004128 if (PyBytes_Check(rep)) {
4129 char *prep = PyBytes_AS_STRING(rep);
4130 for(k = repsize; k > 0; k--)
4131 *p++ = *prep++;
4132 } else /* rep is unicode */ {
4133 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4134 Py_UNICODE c;
4135
4136 for(k=0; k<repsize; k++) {
4137 c = prep[k];
4138 if (0x80 <= c) {
4139 raise_encode_exception(&exc, "utf-8",
4140 PyUnicode_AS_UNICODE(unicode),
4141 size, i-1, i,
4142 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004143 goto error;
4144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004145 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004146 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004148 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004149 } else if (ch < 0x10000) {
4150 *p++ = (char)(0xe0 | (ch >> 12));
4151 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4152 *p++ = (char)(0x80 | (ch & 0x3f));
4153 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004154 /* Encode UCS4 Unicode ordinals */
4155 *p++ = (char)(0xf0 | (ch >> 18));
4156 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4157 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4158 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004159#if SIZEOF_WCHAR_T == 2
4160 wchar_offset++;
4161#endif
Tim Peters602f7402002-04-27 18:03:26 +00004162 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004163 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004164
Guido van Rossum98297ee2007-11-06 21:34:58 +00004165 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004166 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004167 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004168 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004169 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004170 }
4171 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004172 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004173 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004174 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004175 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004176 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004177
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004178 Py_XDECREF(errorHandler);
4179 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004180 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004181 error:
4182 Py_XDECREF(errorHandler);
4183 Py_XDECREF(exc);
4184 Py_XDECREF(result);
4185 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004186
Tim Peters602f7402002-04-27 18:03:26 +00004187#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004188}
4189
Alexander Belopolsky40018472011-02-26 01:02:56 +00004190PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004191PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4192 Py_ssize_t size,
4193 const char *errors)
4194{
4195 PyObject *v, *unicode;
4196
4197 unicode = PyUnicode_FromUnicode(s, size);
4198 if (unicode == NULL)
4199 return NULL;
4200 v = _PyUnicode_AsUTF8String(unicode, errors);
4201 Py_DECREF(unicode);
4202 return v;
4203}
4204
4205PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004206PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004208 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004209}
4210
Walter Dörwald41980ca2007-08-16 21:55:45 +00004211/* --- UTF-32 Codec ------------------------------------------------------- */
4212
4213PyObject *
4214PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004215 Py_ssize_t size,
4216 const char *errors,
4217 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004218{
4219 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4220}
4221
4222PyObject *
4223PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004224 Py_ssize_t size,
4225 const char *errors,
4226 int *byteorder,
4227 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004228{
4229 const char *starts = s;
4230 Py_ssize_t startinpos;
4231 Py_ssize_t endinpos;
4232 Py_ssize_t outpos;
4233 PyUnicodeObject *unicode;
4234 Py_UNICODE *p;
4235#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004236 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004237 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004238#else
4239 const int pairs = 0;
4240#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004241 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004242 int bo = 0; /* assume native ordering by default */
4243 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004244 /* Offsets from q for retrieving bytes in the right order. */
4245#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4246 int iorder[] = {0, 1, 2, 3};
4247#else
4248 int iorder[] = {3, 2, 1, 0};
4249#endif
4250 PyObject *errorHandler = NULL;
4251 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004252
Walter Dörwald41980ca2007-08-16 21:55:45 +00004253 q = (unsigned char *)s;
4254 e = q + size;
4255
4256 if (byteorder)
4257 bo = *byteorder;
4258
4259 /* Check for BOM marks (U+FEFF) in the input and adjust current
4260 byte order setting accordingly. In native mode, the leading BOM
4261 mark is skipped, in all other modes, it is copied to the output
4262 stream as-is (giving a ZWNBSP character). */
4263 if (bo == 0) {
4264 if (size >= 4) {
4265 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004266 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004267#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004268 if (bom == 0x0000FEFF) {
4269 q += 4;
4270 bo = -1;
4271 }
4272 else if (bom == 0xFFFE0000) {
4273 q += 4;
4274 bo = 1;
4275 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004276#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004277 if (bom == 0x0000FEFF) {
4278 q += 4;
4279 bo = 1;
4280 }
4281 else if (bom == 0xFFFE0000) {
4282 q += 4;
4283 bo = -1;
4284 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004285#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004286 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004287 }
4288
4289 if (bo == -1) {
4290 /* force LE */
4291 iorder[0] = 0;
4292 iorder[1] = 1;
4293 iorder[2] = 2;
4294 iorder[3] = 3;
4295 }
4296 else if (bo == 1) {
4297 /* force BE */
4298 iorder[0] = 3;
4299 iorder[1] = 2;
4300 iorder[2] = 1;
4301 iorder[3] = 0;
4302 }
4303
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004304 /* On narrow builds we split characters outside the BMP into two
4305 codepoints => count how much extra space we need. */
4306#ifndef Py_UNICODE_WIDE
4307 for (qq = q; qq < e; qq += 4)
4308 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4309 pairs++;
4310#endif
4311
4312 /* This might be one to much, because of a BOM */
4313 unicode = _PyUnicode_New((size+3)/4+pairs);
4314 if (!unicode)
4315 return NULL;
4316 if (size == 0)
4317 return (PyObject *)unicode;
4318
4319 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004320 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004321
Walter Dörwald41980ca2007-08-16 21:55:45 +00004322 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004323 Py_UCS4 ch;
4324 /* remaining bytes at the end? (size should be divisible by 4) */
4325 if (e-q<4) {
4326 if (consumed)
4327 break;
4328 errmsg = "truncated data";
4329 startinpos = ((const char *)q)-starts;
4330 endinpos = ((const char *)e)-starts;
4331 goto utf32Error;
4332 /* The remaining input chars are ignored if the callback
4333 chooses to skip the input */
4334 }
4335 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4336 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004337
Benjamin Peterson29060642009-01-31 22:14:21 +00004338 if (ch >= 0x110000)
4339 {
4340 errmsg = "codepoint not in range(0x110000)";
4341 startinpos = ((const char *)q)-starts;
4342 endinpos = startinpos+4;
4343 goto utf32Error;
4344 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004345#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004346 if (ch >= 0x10000)
4347 {
4348 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4349 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4350 }
4351 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004352#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004353 *p++ = ch;
4354 q += 4;
4355 continue;
4356 utf32Error:
4357 outpos = p-PyUnicode_AS_UNICODE(unicode);
4358 if (unicode_decode_call_errorhandler(
4359 errors, &errorHandler,
4360 "utf32", errmsg,
4361 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4362 &unicode, &outpos, &p))
4363 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004364 }
4365
4366 if (byteorder)
4367 *byteorder = bo;
4368
4369 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004370 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004371
4372 /* Adjust length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004373 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004374 goto onError;
4375
4376 Py_XDECREF(errorHandler);
4377 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378 if (PyUnicode_READY(unicode) == -1) {
4379 Py_DECREF(unicode);
4380 return NULL;
4381 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004382 return (PyObject *)unicode;
4383
Benjamin Peterson29060642009-01-31 22:14:21 +00004384 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004385 Py_DECREF(unicode);
4386 Py_XDECREF(errorHandler);
4387 Py_XDECREF(exc);
4388 return NULL;
4389}
4390
4391PyObject *
4392PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 Py_ssize_t size,
4394 const char *errors,
4395 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004396{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004397 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004398 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004399 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004400#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004401 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004402#else
4403 const int pairs = 0;
4404#endif
4405 /* Offsets from p for storing byte pairs in the right order. */
4406#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4407 int iorder[] = {0, 1, 2, 3};
4408#else
4409 int iorder[] = {3, 2, 1, 0};
4410#endif
4411
Benjamin Peterson29060642009-01-31 22:14:21 +00004412#define STORECHAR(CH) \
4413 do { \
4414 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4415 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4416 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4417 p[iorder[0]] = (CH) & 0xff; \
4418 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004419 } while(0)
4420
4421 /* In narrow builds we can output surrogate pairs as one codepoint,
4422 so we need less space. */
4423#ifndef Py_UNICODE_WIDE
4424 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004425 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
4426 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
4427 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004428#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004429 nsize = (size - pairs + (byteorder == 0));
4430 bytesize = nsize * 4;
4431 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004432 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004433 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004434 if (v == NULL)
4435 return NULL;
4436
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004437 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004438 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004439 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004440 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004441 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004442
4443 if (byteorder == -1) {
4444 /* force LE */
4445 iorder[0] = 0;
4446 iorder[1] = 1;
4447 iorder[2] = 2;
4448 iorder[3] = 3;
4449 }
4450 else if (byteorder == 1) {
4451 /* force BE */
4452 iorder[0] = 3;
4453 iorder[1] = 2;
4454 iorder[2] = 1;
4455 iorder[3] = 0;
4456 }
4457
4458 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004460#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004461 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
4462 Py_UCS4 ch2 = *s;
4463 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
4464 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
4465 s++;
4466 size--;
4467 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004468 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004469#endif
4470 STORECHAR(ch);
4471 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004472
4473 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004474 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004475#undef STORECHAR
4476}
4477
Alexander Belopolsky40018472011-02-26 01:02:56 +00004478PyObject *
4479PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004480{
4481 if (!PyUnicode_Check(unicode)) {
4482 PyErr_BadArgument();
4483 return NULL;
4484 }
4485 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004486 PyUnicode_GET_SIZE(unicode),
4487 NULL,
4488 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004489}
4490
Guido van Rossumd57fd912000-03-10 22:53:23 +00004491/* --- UTF-16 Codec ------------------------------------------------------- */
4492
Tim Peters772747b2001-08-09 22:21:55 +00004493PyObject *
4494PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 Py_ssize_t size,
4496 const char *errors,
4497 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004498{
Walter Dörwald69652032004-09-07 20:24:22 +00004499 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
4500}
4501
Antoine Pitrouab868312009-01-10 15:40:25 +00004502/* Two masks for fast checking of whether a C 'long' may contain
4503 UTF16-encoded surrogate characters. This is an efficient heuristic,
4504 assuming that non-surrogate characters with a code point >= 0x8000 are
4505 rare in most input.
4506 FAST_CHAR_MASK is used when the input is in native byte ordering,
4507 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00004508*/
Antoine Pitrouab868312009-01-10 15:40:25 +00004509#if (SIZEOF_LONG == 8)
4510# define FAST_CHAR_MASK 0x8000800080008000L
4511# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
4512#elif (SIZEOF_LONG == 4)
4513# define FAST_CHAR_MASK 0x80008000L
4514# define SWAPPED_FAST_CHAR_MASK 0x00800080L
4515#else
4516# error C 'long' size should be either 4 or 8!
4517#endif
4518
Walter Dörwald69652032004-09-07 20:24:22 +00004519PyObject *
4520PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004521 Py_ssize_t size,
4522 const char *errors,
4523 int *byteorder,
4524 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004525{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004526 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004527 Py_ssize_t startinpos;
4528 Py_ssize_t endinpos;
4529 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004530 PyUnicodeObject *unicode;
4531 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004532 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00004533 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00004534 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004535 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00004536 /* Offsets from q for retrieving byte pairs in the right order. */
4537#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4538 int ihi = 1, ilo = 0;
4539#else
4540 int ihi = 0, ilo = 1;
4541#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004542 PyObject *errorHandler = NULL;
4543 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004544
4545 /* Note: size will always be longer than the resulting Unicode
4546 character count */
4547 unicode = _PyUnicode_New(size);
4548 if (!unicode)
4549 return NULL;
4550 if (size == 0)
4551 return (PyObject *)unicode;
4552
4553 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004554 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00004555 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00004556 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004557
4558 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00004559 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004560
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004561 /* Check for BOM marks (U+FEFF) in the input and adjust current
4562 byte order setting accordingly. In native mode, the leading BOM
4563 mark is skipped, in all other modes, it is copied to the output
4564 stream as-is (giving a ZWNBSP character). */
4565 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00004566 if (size >= 2) {
4567 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004568#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004569 if (bom == 0xFEFF) {
4570 q += 2;
4571 bo = -1;
4572 }
4573 else if (bom == 0xFFFE) {
4574 q += 2;
4575 bo = 1;
4576 }
Tim Petersced69f82003-09-16 20:30:58 +00004577#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004578 if (bom == 0xFEFF) {
4579 q += 2;
4580 bo = 1;
4581 }
4582 else if (bom == 0xFFFE) {
4583 q += 2;
4584 bo = -1;
4585 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004586#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004587 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004588 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004589
Tim Peters772747b2001-08-09 22:21:55 +00004590 if (bo == -1) {
4591 /* force LE */
4592 ihi = 1;
4593 ilo = 0;
4594 }
4595 else if (bo == 1) {
4596 /* force BE */
4597 ihi = 0;
4598 ilo = 1;
4599 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004600#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4601 native_ordering = ilo < ihi;
4602#else
4603 native_ordering = ilo > ihi;
4604#endif
Tim Peters772747b2001-08-09 22:21:55 +00004605
Antoine Pitrouab868312009-01-10 15:40:25 +00004606 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00004607 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004608 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00004609 /* First check for possible aligned read of a C 'long'. Unaligned
4610 reads are more expensive, better to defer to another iteration. */
4611 if (!((size_t) q & LONG_PTR_MASK)) {
4612 /* Fast path for runs of non-surrogate chars. */
4613 register const unsigned char *_q = q;
4614 Py_UNICODE *_p = p;
4615 if (native_ordering) {
4616 /* Native ordering is simple: as long as the input cannot
4617 possibly contain a surrogate char, do an unrolled copy
4618 of several 16-bit code points to the target object.
4619 The non-surrogate check is done on several input bytes
4620 at a time (as many as a C 'long' can contain). */
4621 while (_q < aligned_end) {
4622 unsigned long data = * (unsigned long *) _q;
4623 if (data & FAST_CHAR_MASK)
4624 break;
4625 _p[0] = ((unsigned short *) _q)[0];
4626 _p[1] = ((unsigned short *) _q)[1];
4627#if (SIZEOF_LONG == 8)
4628 _p[2] = ((unsigned short *) _q)[2];
4629 _p[3] = ((unsigned short *) _q)[3];
4630#endif
4631 _q += SIZEOF_LONG;
4632 _p += SIZEOF_LONG / 2;
4633 }
4634 }
4635 else {
4636 /* Byteswapped ordering is similar, but we must decompose
4637 the copy bytewise, and take care of zero'ing out the
4638 upper bytes if the target object is in 32-bit units
4639 (that is, in UCS-4 builds). */
4640 while (_q < aligned_end) {
4641 unsigned long data = * (unsigned long *) _q;
4642 if (data & SWAPPED_FAST_CHAR_MASK)
4643 break;
4644 /* Zero upper bytes in UCS-4 builds */
4645#if (Py_UNICODE_SIZE > 2)
4646 _p[0] = 0;
4647 _p[1] = 0;
4648#if (SIZEOF_LONG == 8)
4649 _p[2] = 0;
4650 _p[3] = 0;
4651#endif
4652#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004653 /* Issue #4916; UCS-4 builds on big endian machines must
4654 fill the two last bytes of each 4-byte unit. */
4655#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
4656# define OFF 2
4657#else
4658# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00004659#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004660 ((unsigned char *) _p)[OFF + 1] = _q[0];
4661 ((unsigned char *) _p)[OFF + 0] = _q[1];
4662 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
4663 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
4664#if (SIZEOF_LONG == 8)
4665 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
4666 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
4667 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
4668 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
4669#endif
4670#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00004671 _q += SIZEOF_LONG;
4672 _p += SIZEOF_LONG / 2;
4673 }
4674 }
4675 p = _p;
4676 q = _q;
4677 if (q >= e)
4678 break;
4679 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004680 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004681
Benjamin Peterson14339b62009-01-31 16:36:08 +00004682 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00004683
4684 if (ch < 0xD800 || ch > 0xDFFF) {
4685 *p++ = ch;
4686 continue;
4687 }
4688
4689 /* UTF-16 code pair: */
4690 if (q > e) {
4691 errmsg = "unexpected end of data";
4692 startinpos = (((const char *)q) - 2) - starts;
4693 endinpos = ((const char *)e) + 1 - starts;
4694 goto utf16Error;
4695 }
4696 if (0xD800 <= ch && ch <= 0xDBFF) {
4697 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
4698 q += 2;
4699 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00004700#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004701 *p++ = ch;
4702 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004703#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004704 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004705#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004706 continue;
4707 }
4708 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004709 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00004710 startinpos = (((const char *)q)-4)-starts;
4711 endinpos = startinpos+2;
4712 goto utf16Error;
4713 }
4714
Benjamin Peterson14339b62009-01-31 16:36:08 +00004715 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004716 errmsg = "illegal encoding";
4717 startinpos = (((const char *)q)-2)-starts;
4718 endinpos = startinpos+2;
4719 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004720
Benjamin Peterson29060642009-01-31 22:14:21 +00004721 utf16Error:
4722 outpos = p - PyUnicode_AS_UNICODE(unicode);
4723 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00004724 errors,
4725 &errorHandler,
4726 "utf16", errmsg,
4727 &starts,
4728 (const char **)&e,
4729 &startinpos,
4730 &endinpos,
4731 &exc,
4732 (const char **)&q,
4733 &unicode,
4734 &outpos,
4735 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00004736 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004737 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004738 /* remaining byte at the end? (size should be even) */
4739 if (e == q) {
4740 if (!consumed) {
4741 errmsg = "truncated data";
4742 startinpos = ((const char *)q) - starts;
4743 endinpos = ((const char *)e) + 1 - starts;
4744 outpos = p - PyUnicode_AS_UNICODE(unicode);
4745 if (unicode_decode_call_errorhandler(
4746 errors,
4747 &errorHandler,
4748 "utf16", errmsg,
4749 &starts,
4750 (const char **)&e,
4751 &startinpos,
4752 &endinpos,
4753 &exc,
4754 (const char **)&q,
4755 &unicode,
4756 &outpos,
4757 &p))
4758 goto onError;
4759 /* The remaining input chars are ignored if the callback
4760 chooses to skip the input */
4761 }
4762 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004763
4764 if (byteorder)
4765 *byteorder = bo;
4766
Walter Dörwald69652032004-09-07 20:24:22 +00004767 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004768 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00004769
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770 /* Adjust length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004771 if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772 goto onError;
4773
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004774 Py_XDECREF(errorHandler);
4775 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 if (PyUnicode_READY(unicode) == -1) {
4777 Py_DECREF(unicode);
4778 return NULL;
4779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004780 return (PyObject *)unicode;
4781
Benjamin Peterson29060642009-01-31 22:14:21 +00004782 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004784 Py_XDECREF(errorHandler);
4785 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004786 return NULL;
4787}
4788
Antoine Pitrouab868312009-01-10 15:40:25 +00004789#undef FAST_CHAR_MASK
4790#undef SWAPPED_FAST_CHAR_MASK
4791
Tim Peters772747b2001-08-09 22:21:55 +00004792PyObject *
4793PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004794 Py_ssize_t size,
4795 const char *errors,
4796 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004798 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00004799 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004800 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004801#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004802 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004803#else
4804 const int pairs = 0;
4805#endif
Tim Peters772747b2001-08-09 22:21:55 +00004806 /* Offsets from p for storing byte pairs in the right order. */
4807#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4808 int ihi = 1, ilo = 0;
4809#else
4810 int ihi = 0, ilo = 1;
4811#endif
4812
Benjamin Peterson29060642009-01-31 22:14:21 +00004813#define STORECHAR(CH) \
4814 do { \
4815 p[ihi] = ((CH) >> 8) & 0xff; \
4816 p[ilo] = (CH) & 0xff; \
4817 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00004818 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004819
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004820#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004821 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004822 if (s[i] >= 0x10000)
4823 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004824#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004825 /* 2 * (size + pairs + (byteorder == 0)) */
4826 if (size > PY_SSIZE_T_MAX ||
4827 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00004828 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004829 nsize = size + pairs + (byteorder == 0);
4830 bytesize = nsize * 2;
4831 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004832 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004833 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004834 if (v == NULL)
4835 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004836
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004837 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004839 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00004840 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004841 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00004842
4843 if (byteorder == -1) {
4844 /* force LE */
4845 ihi = 1;
4846 ilo = 0;
4847 }
4848 else if (byteorder == 1) {
4849 /* force BE */
4850 ihi = 0;
4851 ilo = 1;
4852 }
4853
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004854 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004855 Py_UNICODE ch = *s++;
4856 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004857#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 if (ch >= 0x10000) {
4859 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
4860 ch = 0xD800 | ((ch-0x10000) >> 10);
4861 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004862#endif
Tim Peters772747b2001-08-09 22:21:55 +00004863 STORECHAR(ch);
4864 if (ch2)
4865 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004866 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004867
4868 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004869 return v;
Tim Peters772747b2001-08-09 22:21:55 +00004870#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871}
4872
Alexander Belopolsky40018472011-02-26 01:02:56 +00004873PyObject *
4874PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004875{
4876 if (!PyUnicode_Check(unicode)) {
4877 PyErr_BadArgument();
4878 return NULL;
4879 }
4880 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004881 PyUnicode_GET_SIZE(unicode),
4882 NULL,
4883 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004884}
4885
4886/* --- Unicode Escape Codec ----------------------------------------------- */
4887
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004888/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
4889 if all the escapes in the string make it still a valid ASCII string.
4890 Returns -1 if any escapes were found which cause the string to
4891 pop out of ASCII range. Otherwise returns the length of the
4892 required buffer to hold the string.
4893 */
4894Py_ssize_t
4895length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
4896{
4897 const unsigned char *p = (const unsigned char *)s;
4898 const unsigned char *end = p + size;
4899 Py_ssize_t length = 0;
4900
4901 if (size < 0)
4902 return -1;
4903
4904 for (; p < end; ++p) {
4905 if (*p > 127) {
4906 /* Non-ASCII */
4907 return -1;
4908 }
4909 else if (*p != '\\') {
4910 /* Normal character */
4911 ++length;
4912 }
4913 else {
4914 /* Backslash-escape, check next char */
4915 ++p;
4916 /* Escape sequence reaches till end of string or
4917 non-ASCII follow-up. */
4918 if (p >= end || *p > 127)
4919 return -1;
4920 switch (*p) {
4921 case '\n':
4922 /* backslash + \n result in zero characters */
4923 break;
4924 case '\\': case '\'': case '\"':
4925 case 'b': case 'f': case 't':
4926 case 'n': case 'r': case 'v': case 'a':
4927 ++length;
4928 break;
4929 case '0': case '1': case '2': case '3':
4930 case '4': case '5': case '6': case '7':
4931 case 'x': case 'u': case 'U': case 'N':
4932 /* these do not guarantee ASCII characters */
4933 return -1;
4934 default:
4935 /* count the backslash + the other character */
4936 length += 2;
4937 }
4938 }
4939 }
4940 return length;
4941}
4942
4943/* Similar to PyUnicode_WRITE but either write into wstr field
4944 or treat string as ASCII. */
4945#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
4946 do { \
4947 if ((kind) != PyUnicode_WCHAR_KIND) \
4948 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4949 else \
4950 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4951 } while (0)
4952
4953#define WRITE_WSTR(buf, index, value) \
4954 assert(kind == PyUnicode_WCHAR_KIND), \
4955 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
4956
4957
Fredrik Lundh06d12682001-01-24 07:59:11 +00004958static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00004959
Alexander Belopolsky40018472011-02-26 01:02:56 +00004960PyObject *
4961PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004962 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02004963 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004964{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004965 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004966 Py_ssize_t startinpos;
4967 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004968 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004969 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004970 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004971 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00004972 char* message;
4973 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004974 PyObject *errorHandler = NULL;
4975 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004976 Py_ssize_t ascii_length;
4977 Py_ssize_t i;
4978 int kind;
4979 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00004980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004981 ascii_length = length_of_escaped_ascii_string(s, size);
4982
4983 /* After length_of_escaped_ascii_string() there are two alternatives,
4984 either the string is pure ASCII with named escapes like \n, etc.
4985 and we determined it's exact size (common case)
4986 or it contains \x, \u, ... escape sequences. then we create a
4987 legacy wchar string and resize it at the end of this function. */
4988 if (ascii_length >= 0) {
4989 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
4990 if (!v)
4991 goto onError;
4992 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
4993 kind = PyUnicode_1BYTE_KIND;
4994 data = PyUnicode_DATA(v);
4995 }
4996 else {
4997 /* Escaped strings will always be longer than the resulting
4998 Unicode string, so we start with size here and then reduce the
4999 length after conversion to the true value.
5000 (but if the error callback returns a long replacement string
5001 we'll have to allocate more space) */
5002 v = _PyUnicode_New(size);
5003 if (!v)
5004 goto onError;
5005 kind = PyUnicode_WCHAR_KIND;
5006 data = PyUnicode_AS_UNICODE(v);
5007 }
5008
Guido van Rossumd57fd912000-03-10 22:53:23 +00005009 if (size == 0)
5010 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005011 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005012 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005013
Guido van Rossumd57fd912000-03-10 22:53:23 +00005014 while (s < end) {
5015 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005016 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005017 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005019 if (kind == PyUnicode_WCHAR_KIND) {
5020 assert(i < _PyUnicode_WSTR_LENGTH(v));
5021 }
5022 else {
5023 /* The only case in which i == ascii_length is a backslash
5024 followed by a newline. */
5025 assert(i <= ascii_length);
5026 }
5027
Guido van Rossumd57fd912000-03-10 22:53:23 +00005028 /* Non-escape characters are interpreted as Unicode ordinals */
5029 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005030 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005031 continue;
5032 }
5033
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005034 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005035 /* \ - Escapes */
5036 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005037 c = *s++;
5038 if (s > end)
5039 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005040
5041 if (kind == PyUnicode_WCHAR_KIND) {
5042 assert(i < _PyUnicode_WSTR_LENGTH(v));
5043 }
5044 else {
5045 /* The only case in which i == ascii_length is a backslash
5046 followed by a newline. */
5047 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5048 }
5049
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005050 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005051
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005053 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005054 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5055 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5056 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5057 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5058 /* FF */
5059 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5060 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5061 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5062 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5063 /* VT */
5064 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5065 /* BEL, not classic C */
5066 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005067
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005069 case '0': case '1': case '2': case '3':
5070 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005071 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005072 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005073 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005074 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005075 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005076 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005077 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005078 break;
5079
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 /* hex escapes */
5081 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005082 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005083 digits = 2;
5084 message = "truncated \\xXX escape";
5085 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005086
Benjamin Peterson29060642009-01-31 22:14:21 +00005087 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005088 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005089 digits = 4;
5090 message = "truncated \\uXXXX escape";
5091 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005092
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005094 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005095 digits = 8;
5096 message = "truncated \\UXXXXXXXX escape";
5097 hexescape:
5098 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005099 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005100 if (s+digits>end) {
5101 endinpos = size;
5102 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005103 errors, &errorHandler,
5104 "unicodeescape", "end of string in escape sequence",
5105 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005106 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005107 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005108 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005109 goto nextByte;
5110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005111 for (j = 0; j < digits; ++j) {
5112 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005113 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005114 endinpos = (s+j+1)-starts;
5115 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005116 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 errors, &errorHandler,
5118 "unicodeescape", message,
5119 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005120 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005121 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005122 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005123 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005124 }
5125 chr = (chr<<4) & ~0xF;
5126 if (c >= '0' && c <= '9')
5127 chr += c - '0';
5128 else if (c >= 'a' && c <= 'f')
5129 chr += 10 + c - 'a';
5130 else
5131 chr += 10 + c - 'A';
5132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005133 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005134 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005135 /* _decoding_error will have already written into the
5136 target buffer. */
5137 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005138 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005139 /* when we get here, chr is a 32-bit unicode character */
5140 if (chr <= 0xffff)
5141 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005142 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005143 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005144 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005145 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005146#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005147 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005148#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005149 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005150 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5151 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005152#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005153 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005154 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005155 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005156 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005157 errors, &errorHandler,
5158 "unicodeescape", "illegal Unicode character",
5159 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005160 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005161 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005162 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005163 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005164 break;
5165
Benjamin Peterson29060642009-01-31 22:14:21 +00005166 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005167 case 'N':
5168 message = "malformed \\N character escape";
5169 if (ucnhash_CAPI == NULL) {
5170 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005171 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5172 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005173 if (ucnhash_CAPI == NULL)
5174 goto ucnhashError;
5175 }
5176 if (*s == '{') {
5177 const char *start = s+1;
5178 /* look for the closing brace */
5179 while (*s != '}' && s < end)
5180 s++;
5181 if (s > start && s < end && *s == '}') {
5182 /* found a name. look it up in the unicode database */
5183 message = "unknown Unicode character name";
5184 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005185 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5186 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005187 goto store;
5188 }
5189 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005190 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005191 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005192 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 errors, &errorHandler,
5194 "unicodeescape", message,
5195 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005196 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005197 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005198 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005199 break;
5200
5201 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005202 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005203 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005204 message = "\\ at end of string";
5205 s--;
5206 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005207 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005208 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005209 errors, &errorHandler,
5210 "unicodeescape", message,
5211 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005212 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005213 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005214 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005215 }
5216 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005217 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5218 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005219 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005220 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005222 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005223 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005225 /* Ensure the length prediction worked in case of ASCII strings */
5226 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5227
5228 if (kind == PyUnicode_WCHAR_KIND && (_PyUnicode_Resize(&v, i) < 0 ||
5229 PyUnicode_READY(v) == -1))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005230 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005231 Py_XDECREF(errorHandler);
5232 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005233 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005234
Benjamin Peterson29060642009-01-31 22:14:21 +00005235 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005236 PyErr_SetString(
5237 PyExc_UnicodeError,
5238 "\\N escapes not supported (can't load unicodedata module)"
5239 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005240 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005241 Py_XDECREF(errorHandler);
5242 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005243 return NULL;
5244
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005246 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005247 Py_XDECREF(errorHandler);
5248 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005249 return NULL;
5250}
5251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005252#undef WRITE_ASCII_OR_WSTR
5253#undef WRITE_WSTR
5254
Guido van Rossumd57fd912000-03-10 22:53:23 +00005255/* Return a Unicode-Escape string version of the Unicode object.
5256
5257 If quotes is true, the string is enclosed in u"" or u'' quotes as
5258 appropriate.
5259
5260*/
5261
Walter Dörwald79e913e2007-05-12 11:08:06 +00005262static const char *hexdigits = "0123456789abcdef";
5263
Alexander Belopolsky40018472011-02-26 01:02:56 +00005264PyObject *
5265PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005266 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005267{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005268 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005269 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005270
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005271#ifdef Py_UNICODE_WIDE
5272 const Py_ssize_t expandsize = 10;
5273#else
5274 const Py_ssize_t expandsize = 6;
5275#endif
5276
Thomas Wouters89f507f2006-12-13 04:49:30 +00005277 /* XXX(nnorwitz): rather than over-allocating, it would be
5278 better to choose a different scheme. Perhaps scan the
5279 first N-chars of the string and allocate based on that size.
5280 */
5281 /* Initial allocation is based on the longest-possible unichr
5282 escape.
5283
5284 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5285 unichr, so in this case it's the longest unichr escape. In
5286 narrow (UTF-16) builds this is five chars per source unichr
5287 since there are two unichrs in the surrogate pair, so in narrow
5288 (UTF-16) builds it's not the longest unichr escape.
5289
5290 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5291 so in the narrow (UTF-16) build case it's the longest unichr
5292 escape.
5293 */
5294
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005295 if (size == 0)
5296 return PyBytes_FromStringAndSize(NULL, 0);
5297
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005298 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005299 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005300
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005301 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 2
5303 + expandsize*size
5304 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005305 if (repr == NULL)
5306 return NULL;
5307
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005308 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005309
Guido van Rossumd57fd912000-03-10 22:53:23 +00005310 while (size-- > 0) {
5311 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005312
Walter Dörwald79e913e2007-05-12 11:08:06 +00005313 /* Escape backslashes */
5314 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005315 *p++ = '\\';
5316 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005317 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005318 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005319
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005320#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005321 /* Map 21-bit characters to '\U00xxxxxx' */
5322 else if (ch >= 0x10000) {
5323 *p++ = '\\';
5324 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005325 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5326 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5327 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5328 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5329 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5330 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5331 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5332 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005334 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005335#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5337 else if (ch >= 0xD800 && ch < 0xDC00) {
5338 Py_UNICODE ch2;
5339 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005340
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 ch2 = *s++;
5342 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005343 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5345 *p++ = '\\';
5346 *p++ = 'U';
5347 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5348 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5349 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5350 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5351 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5352 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5353 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5354 *p++ = hexdigits[ucs & 0x0000000F];
5355 continue;
5356 }
5357 /* Fall through: isolated surrogates are copied as-is */
5358 s--;
5359 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005360 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005361#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005362
Guido van Rossumd57fd912000-03-10 22:53:23 +00005363 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005364 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365 *p++ = '\\';
5366 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005367 *p++ = hexdigits[(ch >> 12) & 0x000F];
5368 *p++ = hexdigits[(ch >> 8) & 0x000F];
5369 *p++ = hexdigits[(ch >> 4) & 0x000F];
5370 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005371 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005372
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005373 /* Map special whitespace to '\t', \n', '\r' */
5374 else if (ch == '\t') {
5375 *p++ = '\\';
5376 *p++ = 't';
5377 }
5378 else if (ch == '\n') {
5379 *p++ = '\\';
5380 *p++ = 'n';
5381 }
5382 else if (ch == '\r') {
5383 *p++ = '\\';
5384 *p++ = 'r';
5385 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005386
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005387 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005388 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005390 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005391 *p++ = hexdigits[(ch >> 4) & 0x000F];
5392 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005393 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005394
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395 /* Copy everything else as-is */
5396 else
5397 *p++ = (char) ch;
5398 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005399
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005400 assert(p - PyBytes_AS_STRING(repr) > 0);
5401 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5402 return NULL;
5403 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404}
5405
Alexander Belopolsky40018472011-02-26 01:02:56 +00005406PyObject *
5407PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005409 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410 if (!PyUnicode_Check(unicode)) {
5411 PyErr_BadArgument();
5412 return NULL;
5413 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005414 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5415 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005416 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417}
5418
5419/* --- Raw Unicode Escape Codec ------------------------------------------- */
5420
Alexander Belopolsky40018472011-02-26 01:02:56 +00005421PyObject *
5422PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005423 Py_ssize_t size,
5424 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005426 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005427 Py_ssize_t startinpos;
5428 Py_ssize_t endinpos;
5429 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005431 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432 const char *end;
5433 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 PyObject *errorHandler = NULL;
5435 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005436
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437 /* Escaped strings will always be longer than the resulting
5438 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005439 length after conversion to the true value. (But decoding error
5440 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 v = _PyUnicode_New(size);
5442 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005445 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005446 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447 end = s + size;
5448 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005449 unsigned char c;
5450 Py_UCS4 x;
5451 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005452 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453
Benjamin Peterson29060642009-01-31 22:14:21 +00005454 /* Non-escape characters are interpreted as Unicode ordinals */
5455 if (*s != '\\') {
5456 *p++ = (unsigned char)*s++;
5457 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005458 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005459 startinpos = s-starts;
5460
5461 /* \u-escapes are only interpreted iff the number of leading
5462 backslashes if odd */
5463 bs = s;
5464 for (;s < end;) {
5465 if (*s != '\\')
5466 break;
5467 *p++ = (unsigned char)*s++;
5468 }
5469 if (((s - bs) & 1) == 0 ||
5470 s >= end ||
5471 (*s != 'u' && *s != 'U')) {
5472 continue;
5473 }
5474 p--;
5475 count = *s=='u' ? 4 : 8;
5476 s++;
5477
5478 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
5479 outpos = p-PyUnicode_AS_UNICODE(v);
5480 for (x = 0, i = 0; i < count; ++i, ++s) {
5481 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005482 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 endinpos = s-starts;
5484 if (unicode_decode_call_errorhandler(
5485 errors, &errorHandler,
5486 "rawunicodeescape", "truncated \\uXXXX",
5487 &starts, &end, &startinpos, &endinpos, &exc, &s,
5488 &v, &outpos, &p))
5489 goto onError;
5490 goto nextByte;
5491 }
5492 x = (x<<4) & ~0xF;
5493 if (c >= '0' && c <= '9')
5494 x += c - '0';
5495 else if (c >= 'a' && c <= 'f')
5496 x += 10 + c - 'a';
5497 else
5498 x += 10 + c - 'A';
5499 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00005500 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00005501 /* UCS-2 character */
5502 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005503 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005504 /* UCS-4 character. Either store directly, or as
5505 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00005506#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005507 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005508#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005509 x -= 0x10000L;
5510 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
5511 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00005512#endif
5513 } else {
5514 endinpos = s-starts;
5515 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005516 if (unicode_decode_call_errorhandler(
5517 errors, &errorHandler,
5518 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005519 &starts, &end, &startinpos, &endinpos, &exc, &s,
5520 &v, &outpos, &p))
5521 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005522 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005523 nextByte:
5524 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005526 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005527 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005528 Py_XDECREF(errorHandler);
5529 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005530 if (PyUnicode_READY(v) == -1) {
5531 Py_DECREF(v);
5532 return NULL;
5533 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005534 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005535
Benjamin Peterson29060642009-01-31 22:14:21 +00005536 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005537 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538 Py_XDECREF(errorHandler);
5539 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540 return NULL;
5541}
5542
Alexander Belopolsky40018472011-02-26 01:02:56 +00005543PyObject *
5544PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005545 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005547 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005548 char *p;
5549 char *q;
5550
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005551#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005552 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005553#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005554 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005555#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00005556
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005557 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005558 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005559
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005560 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561 if (repr == NULL)
5562 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005563 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005564 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005565
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005566 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005567 while (size-- > 0) {
5568 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005569#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 /* Map 32-bit characters to '\Uxxxxxxxx' */
5571 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005572 *p++ = '\\';
5573 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005574 *p++ = hexdigits[(ch >> 28) & 0xf];
5575 *p++ = hexdigits[(ch >> 24) & 0xf];
5576 *p++ = hexdigits[(ch >> 20) & 0xf];
5577 *p++ = hexdigits[(ch >> 16) & 0xf];
5578 *p++ = hexdigits[(ch >> 12) & 0xf];
5579 *p++ = hexdigits[(ch >> 8) & 0xf];
5580 *p++ = hexdigits[(ch >> 4) & 0xf];
5581 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005582 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005583 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00005584#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5586 if (ch >= 0xD800 && ch < 0xDC00) {
5587 Py_UNICODE ch2;
5588 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005589
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 ch2 = *s++;
5591 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005592 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005593 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5594 *p++ = '\\';
5595 *p++ = 'U';
5596 *p++ = hexdigits[(ucs >> 28) & 0xf];
5597 *p++ = hexdigits[(ucs >> 24) & 0xf];
5598 *p++ = hexdigits[(ucs >> 20) & 0xf];
5599 *p++ = hexdigits[(ucs >> 16) & 0xf];
5600 *p++ = hexdigits[(ucs >> 12) & 0xf];
5601 *p++ = hexdigits[(ucs >> 8) & 0xf];
5602 *p++ = hexdigits[(ucs >> 4) & 0xf];
5603 *p++ = hexdigits[ucs & 0xf];
5604 continue;
5605 }
5606 /* Fall through: isolated surrogates are copied as-is */
5607 s--;
5608 size++;
5609 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005610#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005611 /* Map 16-bit characters to '\uxxxx' */
5612 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005613 *p++ = '\\';
5614 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005615 *p++ = hexdigits[(ch >> 12) & 0xf];
5616 *p++ = hexdigits[(ch >> 8) & 0xf];
5617 *p++ = hexdigits[(ch >> 4) & 0xf];
5618 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005620 /* Copy everything else as-is */
5621 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005622 *p++ = (char) ch;
5623 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005624 size = p - q;
5625
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005626 assert(size > 0);
5627 if (_PyBytes_Resize(&repr, size) < 0)
5628 return NULL;
5629 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630}
5631
Alexander Belopolsky40018472011-02-26 01:02:56 +00005632PyObject *
5633PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005635 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00005637 PyErr_BadArgument();
5638 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005639 }
Walter Dörwald711005d2007-05-12 12:03:26 +00005640 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5641 PyUnicode_GET_SIZE(unicode));
5642
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005643 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644}
5645
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005646/* --- Unicode Internal Codec ------------------------------------------- */
5647
Alexander Belopolsky40018472011-02-26 01:02:56 +00005648PyObject *
5649_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005650 Py_ssize_t size,
5651 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005652{
5653 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005654 Py_ssize_t startinpos;
5655 Py_ssize_t endinpos;
5656 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005657 PyUnicodeObject *v;
5658 Py_UNICODE *p;
5659 const char *end;
5660 const char *reason;
5661 PyObject *errorHandler = NULL;
5662 PyObject *exc = NULL;
5663
Neal Norwitzd43069c2006-01-08 01:12:10 +00005664#ifdef Py_UNICODE_WIDE
5665 Py_UNICODE unimax = PyUnicode_GetMax();
5666#endif
5667
Thomas Wouters89f507f2006-12-13 04:49:30 +00005668 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005669 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
5670 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005671 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
5673 as string was created with the old API. */
5674 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005676 p = PyUnicode_AS_UNICODE(v);
5677 end = s + size;
5678
5679 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00005680 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005681 /* We have to sanity check the raw data, otherwise doom looms for
5682 some malformed UCS-4 data. */
5683 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00005684#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005685 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00005686#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005687 end-s < Py_UNICODE_SIZE
5688 )
Benjamin Peterson29060642009-01-31 22:14:21 +00005689 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005690 startinpos = s - starts;
5691 if (end-s < Py_UNICODE_SIZE) {
5692 endinpos = end-starts;
5693 reason = "truncated input";
5694 }
5695 else {
5696 endinpos = s - starts + Py_UNICODE_SIZE;
5697 reason = "illegal code point (> 0x10FFFF)";
5698 }
5699 outpos = p - PyUnicode_AS_UNICODE(v);
5700 if (unicode_decode_call_errorhandler(
5701 errors, &errorHandler,
5702 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00005703 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00005704 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005705 goto onError;
5706 }
5707 }
5708 else {
5709 p++;
5710 s += Py_UNICODE_SIZE;
5711 }
5712 }
5713
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005714 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005715 goto onError;
5716 Py_XDECREF(errorHandler);
5717 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005718 if (PyUnicode_READY(v) == -1) {
5719 Py_DECREF(v);
5720 return NULL;
5721 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005722 return (PyObject *)v;
5723
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005725 Py_XDECREF(v);
5726 Py_XDECREF(errorHandler);
5727 Py_XDECREF(exc);
5728 return NULL;
5729}
5730
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731/* --- Latin-1 Codec ------------------------------------------------------ */
5732
Alexander Belopolsky40018472011-02-26 01:02:56 +00005733PyObject *
5734PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005735 Py_ssize_t size,
5736 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737{
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02005739 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740}
5741
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005742/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005743static void
5744make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005745 const char *encoding,
5746 const Py_UNICODE *unicode, Py_ssize_t size,
5747 Py_ssize_t startpos, Py_ssize_t endpos,
5748 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005751 *exceptionObject = PyUnicodeEncodeError_Create(
5752 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753 }
5754 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005755 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
5756 goto onError;
5757 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
5758 goto onError;
5759 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
5760 goto onError;
5761 return;
5762 onError:
5763 Py_DECREF(*exceptionObject);
5764 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005765 }
5766}
5767
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005769static void
5770raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005771 const char *encoding,
5772 const Py_UNICODE *unicode, Py_ssize_t size,
5773 Py_ssize_t startpos, Py_ssize_t endpos,
5774 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775{
5776 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005777 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005780}
5781
5782/* error handling callback helper:
5783 build arguments, call the callback and check the arguments,
5784 put the result into newpos and return the replacement string, which
5785 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005786static PyObject *
5787unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005788 PyObject **errorHandler,
5789 const char *encoding, const char *reason,
5790 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5791 Py_ssize_t startpos, Py_ssize_t endpos,
5792 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005793{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005794 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005795
5796 PyObject *restuple;
5797 PyObject *resunicode;
5798
5799 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005801 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005802 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005803 }
5804
5805 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005807 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005808 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809
5810 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005814 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005815 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 Py_DECREF(restuple);
5817 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005819 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00005820 &resunicode, newpos)) {
5821 Py_DECREF(restuple);
5822 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005823 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005824 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
5825 PyErr_SetString(PyExc_TypeError, &argparse[3]);
5826 Py_DECREF(restuple);
5827 return NULL;
5828 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005829 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005830 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005831 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005832 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
5833 Py_DECREF(restuple);
5834 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00005835 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005836 Py_INCREF(resunicode);
5837 Py_DECREF(restuple);
5838 return resunicode;
5839}
5840
Alexander Belopolsky40018472011-02-26 01:02:56 +00005841static PyObject *
5842unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005843 Py_ssize_t size,
5844 const char *errors,
5845 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005846{
5847 /* output object */
5848 PyObject *res;
5849 /* pointers to the beginning and end+1 of input */
5850 const Py_UNICODE *startp = p;
5851 const Py_UNICODE *endp = p + size;
5852 /* pointer to the beginning of the unencodable characters */
5853 /* const Py_UNICODE *badp = NULL; */
5854 /* pointer into the output */
5855 char *str;
5856 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00005857 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005858 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
5859 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005860 PyObject *errorHandler = NULL;
5861 PyObject *exc = NULL;
5862 /* the following variable is used for caching string comparisons
5863 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
5864 int known_errorHandler = -1;
5865
5866 /* allocate enough for a simple encoding without
5867 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00005868 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00005869 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005870 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005872 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005873 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874 ressize = size;
5875
5876 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878
Benjamin Peterson29060642009-01-31 22:14:21 +00005879 /* can we encode this? */
5880 if (c<limit) {
5881 /* no overflow check, because we know that the space is enough */
5882 *str++ = (char)c;
5883 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005884 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005885 else {
5886 Py_ssize_t unicodepos = p-startp;
5887 Py_ssize_t requiredsize;
5888 PyObject *repunicode;
5889 Py_ssize_t repsize;
5890 Py_ssize_t newpos;
5891 Py_ssize_t respos;
5892 Py_UNICODE *uni2;
5893 /* startpos for collecting unencodable chars */
5894 const Py_UNICODE *collstart = p;
5895 const Py_UNICODE *collend = p;
5896 /* find all unecodable characters */
5897 while ((collend < endp) && ((*collend)>=limit))
5898 ++collend;
5899 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
5900 if (known_errorHandler==-1) {
5901 if ((errors==NULL) || (!strcmp(errors, "strict")))
5902 known_errorHandler = 1;
5903 else if (!strcmp(errors, "replace"))
5904 known_errorHandler = 2;
5905 else if (!strcmp(errors, "ignore"))
5906 known_errorHandler = 3;
5907 else if (!strcmp(errors, "xmlcharrefreplace"))
5908 known_errorHandler = 4;
5909 else
5910 known_errorHandler = 0;
5911 }
5912 switch (known_errorHandler) {
5913 case 1: /* strict */
5914 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
5915 goto onError;
5916 case 2: /* replace */
5917 while (collstart++<collend)
5918 *str++ = '?'; /* fall through */
5919 case 3: /* ignore */
5920 p = collend;
5921 break;
5922 case 4: /* xmlcharrefreplace */
5923 respos = str - PyBytes_AS_STRING(res);
5924 /* determine replacement size (temporarily (mis)uses p) */
5925 for (p = collstart, repsize = 0; p < collend; ++p) {
5926 if (*p<10)
5927 repsize += 2+1+1;
5928 else if (*p<100)
5929 repsize += 2+2+1;
5930 else if (*p<1000)
5931 repsize += 2+3+1;
5932 else if (*p<10000)
5933 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00005934#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005935 else
5936 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00005937#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 else if (*p<100000)
5939 repsize += 2+5+1;
5940 else if (*p<1000000)
5941 repsize += 2+6+1;
5942 else
5943 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005944#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005945 }
5946 requiredsize = respos+repsize+(endp-collend);
5947 if (requiredsize > ressize) {
5948 if (requiredsize<2*ressize)
5949 requiredsize = 2*ressize;
5950 if (_PyBytes_Resize(&res, requiredsize))
5951 goto onError;
5952 str = PyBytes_AS_STRING(res) + respos;
5953 ressize = requiredsize;
5954 }
5955 /* generate replacement (temporarily (mis)uses p) */
5956 for (p = collstart; p < collend; ++p) {
5957 str += sprintf(str, "&#%d;", (int)*p);
5958 }
5959 p = collend;
5960 break;
5961 default:
5962 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
5963 encoding, reason, startp, size, &exc,
5964 collstart-startp, collend-startp, &newpos);
5965 if (repunicode == NULL)
5966 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005967 if (PyBytes_Check(repunicode)) {
5968 /* Directly copy bytes result to output. */
5969 repsize = PyBytes_Size(repunicode);
5970 if (repsize > 1) {
5971 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00005972 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005973 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
5974 Py_DECREF(repunicode);
5975 goto onError;
5976 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00005977 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005978 ressize += repsize-1;
5979 }
5980 memcpy(str, PyBytes_AsString(repunicode), repsize);
5981 str += repsize;
5982 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005983 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00005984 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005985 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* need more space? (at least enough for what we
5987 have+the replacement+the rest of the string, so
5988 we won't have to check space for encodable characters) */
5989 respos = str - PyBytes_AS_STRING(res);
5990 repsize = PyUnicode_GET_SIZE(repunicode);
5991 requiredsize = respos+repsize+(endp-collend);
5992 if (requiredsize > ressize) {
5993 if (requiredsize<2*ressize)
5994 requiredsize = 2*ressize;
5995 if (_PyBytes_Resize(&res, requiredsize)) {
5996 Py_DECREF(repunicode);
5997 goto onError;
5998 }
5999 str = PyBytes_AS_STRING(res) + respos;
6000 ressize = requiredsize;
6001 }
6002 /* check if there is anything unencodable in the replacement
6003 and copy it to the output */
6004 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6005 c = *uni2;
6006 if (c >= limit) {
6007 raise_encode_exception(&exc, encoding, startp, size,
6008 unicodepos, unicodepos+1, reason);
6009 Py_DECREF(repunicode);
6010 goto onError;
6011 }
6012 *str = (char)c;
6013 }
6014 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006015 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006016 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006017 }
6018 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006019 /* Resize if we allocated to much */
6020 size = str - PyBytes_AS_STRING(res);
6021 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006022 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006023 if (_PyBytes_Resize(&res, size) < 0)
6024 goto onError;
6025 }
6026
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006027 Py_XDECREF(errorHandler);
6028 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006029 return res;
6030
6031 onError:
6032 Py_XDECREF(res);
6033 Py_XDECREF(errorHandler);
6034 Py_XDECREF(exc);
6035 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006036}
6037
Alexander Belopolsky40018472011-02-26 01:02:56 +00006038PyObject *
6039PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006040 Py_ssize_t size,
6041 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006043 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044}
6045
Alexander Belopolsky40018472011-02-26 01:02:56 +00006046PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006047_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048{
6049 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 PyErr_BadArgument();
6051 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006053 if (PyUnicode_READY(unicode) == -1)
6054 return NULL;
6055 /* Fast path: if it is a one-byte string, construct
6056 bytes object directly. */
6057 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6058 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6059 PyUnicode_GET_LENGTH(unicode));
6060 /* Non-Latin-1 characters present. Defer to above function to
6061 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006064 errors);
6065}
6066
6067PyObject*
6068PyUnicode_AsLatin1String(PyObject *unicode)
6069{
6070 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071}
6072
6073/* --- 7-bit ASCII Codec -------------------------------------------------- */
6074
Alexander Belopolsky40018472011-02-26 01:02:56 +00006075PyObject *
6076PyUnicode_DecodeASCII(const char *s,
6077 Py_ssize_t size,
6078 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006080 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 PyUnicodeObject *v;
6082 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006083 Py_ssize_t startinpos;
6084 Py_ssize_t endinpos;
6085 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006086 const char *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006087 unsigned char* d;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 PyObject *errorHandler = NULL;
6089 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006090 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00006091
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006093 if (size == 1 && *(unsigned char*)s < 128)
6094 return PyUnicode_FromOrdinal(*(unsigned char*)s);
6095
6096 /* Fast path. Assume the input actually *is* ASCII, and allocate
6097 a single-block Unicode object with that assumption. If there is
6098 an error, drop the object and start over. */
6099 v = (PyUnicodeObject*)PyUnicode_New(size, 127);
6100 if (v == NULL)
6101 goto onError;
6102 d = PyUnicode_1BYTE_DATA(v);
6103 for (i = 0; i < size; i++) {
6104 unsigned char ch = ((unsigned char*)s)[i];
6105 if (ch < 128)
6106 d[i] = ch;
6107 else
6108 break;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006109 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006110 if (i == size)
6111 return (PyObject*)v;
6112 Py_DECREF(v); /* start over */
Tim Petersced69f82003-09-16 20:30:58 +00006113
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114 v = _PyUnicode_New(size);
6115 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006120 e = s + size;
6121 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 register unsigned char c = (unsigned char)*s;
6123 if (c < 128) {
6124 *p++ = c;
6125 ++s;
6126 }
6127 else {
6128 startinpos = s-starts;
6129 endinpos = startinpos + 1;
6130 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
6131 if (unicode_decode_call_errorhandler(
6132 errors, &errorHandler,
6133 "ascii", "ordinal not in range(128)",
6134 &starts, &e, &startinpos, &endinpos, &exc, &s,
6135 &v, &outpos, &p))
6136 goto onError;
6137 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00006139 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
6141 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006142 Py_XDECREF(errorHandler);
6143 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006144 if (PyUnicode_READY(v) == -1) {
6145 Py_DECREF(v);
6146 return NULL;
6147 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006149
Benjamin Peterson29060642009-01-31 22:14:21 +00006150 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006152 Py_XDECREF(errorHandler);
6153 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 return NULL;
6155}
6156
Alexander Belopolsky40018472011-02-26 01:02:56 +00006157PyObject *
6158PyUnicode_EncodeASCII(const Py_UNICODE *p,
6159 Py_ssize_t size,
6160 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006162 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163}
6164
Alexander Belopolsky40018472011-02-26 01:02:56 +00006165PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006166_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167{
6168 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 PyErr_BadArgument();
6170 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006172 if (PyUnicode_READY(unicode) == -1)
6173 return NULL;
6174 /* Fast path: if it is an ASCII-only string, construct bytes object
6175 directly. Else defer to above function to raise the exception. */
6176 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6177 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6178 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006179 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006181 errors);
6182}
6183
6184PyObject *
6185PyUnicode_AsASCIIString(PyObject *unicode)
6186{
6187 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188}
6189
Victor Stinner99b95382011-07-04 14:23:54 +02006190#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006191
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006192/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006193
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006194#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006195#define NEED_RETRY
6196#endif
6197
6198/* XXX This code is limited to "true" double-byte encodings, as
6199 a) it assumes an incomplete character consists of a single byte, and
6200 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006202
Alexander Belopolsky40018472011-02-26 01:02:56 +00006203static int
6204is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006205{
6206 const char *curr = s + offset;
6207
6208 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006209 const char *prev = CharPrev(s, curr);
6210 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006211 }
6212 return 0;
6213}
6214
6215/*
6216 * Decode MBCS string into unicode object. If 'final' is set, converts
6217 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6218 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006219static int
6220decode_mbcs(PyUnicodeObject **v,
6221 const char *s, /* MBCS string */
6222 int size, /* sizeof MBCS string */
6223 int final,
6224 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006225{
6226 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006227 Py_ssize_t n;
6228 DWORD usize;
6229 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006230
6231 assert(size >= 0);
6232
Victor Stinner554f3f02010-06-16 23:33:54 +00006233 /* check and handle 'errors' arg */
6234 if (errors==NULL || strcmp(errors, "strict")==0)
6235 flags = MB_ERR_INVALID_CHARS;
6236 else if (strcmp(errors, "ignore")==0)
6237 flags = 0;
6238 else {
6239 PyErr_Format(PyExc_ValueError,
6240 "mbcs encoding does not support errors='%s'",
6241 errors);
6242 return -1;
6243 }
6244
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006245 /* Skip trailing lead-byte unless 'final' is set */
6246 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006247 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006248
6249 /* First get the size of the result */
6250 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006251 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6252 if (usize==0)
6253 goto mbcs_decode_error;
6254 } else
6255 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006256
6257 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 /* Create unicode object */
6259 *v = _PyUnicode_New(usize);
6260 if (*v == NULL)
6261 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006262 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006263 }
6264 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 /* Extend unicode object */
6266 n = PyUnicode_GET_SIZE(*v);
6267 if (_PyUnicode_Resize(v, n + usize) < 0)
6268 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006269 }
6270
6271 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006272 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006274 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6275 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006277 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006278 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006279
6280mbcs_decode_error:
6281 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6282 we raise a UnicodeDecodeError - else it is a 'generic'
6283 windows error
6284 */
6285 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6286 /* Ideally, we should get reason from FormatMessage - this
6287 is the Windows 2000 English version of the message
6288 */
6289 PyObject *exc = NULL;
6290 const char *reason = "No mapping for the Unicode character exists "
6291 "in the target multi-byte code page.";
6292 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6293 if (exc != NULL) {
6294 PyCodec_StrictErrors(exc);
6295 Py_DECREF(exc);
6296 }
6297 } else {
6298 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6299 }
6300 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006301}
6302
Alexander Belopolsky40018472011-02-26 01:02:56 +00006303PyObject *
6304PyUnicode_DecodeMBCSStateful(const char *s,
6305 Py_ssize_t size,
6306 const char *errors,
6307 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006308{
6309 PyUnicodeObject *v = NULL;
6310 int done;
6311
6312 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006314
6315#ifdef NEED_RETRY
6316 retry:
6317 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006318 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006319 else
6320#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006321 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006322
6323 if (done < 0) {
6324 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006325 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006326 }
6327
6328 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006329 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006330
6331#ifdef NEED_RETRY
6332 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 s += done;
6334 size -= done;
6335 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006336 }
6337#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006338 if (PyUnicode_READY(v) == -1) {
6339 Py_DECREF(v);
6340 return NULL;
6341 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006342 return (PyObject *)v;
6343}
6344
Alexander Belopolsky40018472011-02-26 01:02:56 +00006345PyObject *
6346PyUnicode_DecodeMBCS(const char *s,
6347 Py_ssize_t size,
6348 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006349{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006350 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6351}
6352
6353/*
6354 * Convert unicode into string object (MBCS).
6355 * Returns 0 if succeed, -1 otherwise.
6356 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357static int
6358encode_mbcs(PyObject **repr,
6359 const Py_UNICODE *p, /* unicode */
6360 int size, /* size of unicode */
6361 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006362{
Victor Stinner554f3f02010-06-16 23:33:54 +00006363 BOOL usedDefaultChar = FALSE;
6364 BOOL *pusedDefaultChar;
6365 int mbcssize;
6366 Py_ssize_t n;
6367 PyObject *exc = NULL;
6368 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006369
6370 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006371
Victor Stinner554f3f02010-06-16 23:33:54 +00006372 /* check and handle 'errors' arg */
6373 if (errors==NULL || strcmp(errors, "strict")==0) {
6374 flags = WC_NO_BEST_FIT_CHARS;
6375 pusedDefaultChar = &usedDefaultChar;
6376 } else if (strcmp(errors, "replace")==0) {
6377 flags = 0;
6378 pusedDefaultChar = NULL;
6379 } else {
6380 PyErr_Format(PyExc_ValueError,
6381 "mbcs encoding does not support errors='%s'",
6382 errors);
6383 return -1;
6384 }
6385
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006386 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006387 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006388 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
6389 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00006390 if (mbcssize == 0) {
6391 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6392 return -1;
6393 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006394 /* If we used a default char, then we failed! */
6395 if (pusedDefaultChar && *pusedDefaultChar)
6396 goto mbcs_encode_error;
6397 } else {
6398 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006399 }
6400
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006401 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 /* Create string object */
6403 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
6404 if (*repr == NULL)
6405 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006406 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006407 }
6408 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 /* Extend string object */
6410 n = PyBytes_Size(*repr);
6411 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
6412 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006413 }
6414
6415 /* Do the conversion */
6416 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006417 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006418 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
6419 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6421 return -1;
6422 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006423 if (pusedDefaultChar && *pusedDefaultChar)
6424 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006425 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006426 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006427
6428mbcs_encode_error:
6429 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
6430 Py_XDECREF(exc);
6431 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006432}
6433
Alexander Belopolsky40018472011-02-26 01:02:56 +00006434PyObject *
6435PyUnicode_EncodeMBCS(const Py_UNICODE *p,
6436 Py_ssize_t size,
6437 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006438{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006439 PyObject *repr = NULL;
6440 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00006441
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006442#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006444 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006445 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006446 else
6447#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006448 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006449
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006450 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 Py_XDECREF(repr);
6452 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006453 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006454
6455#ifdef NEED_RETRY
6456 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 p += INT_MAX;
6458 size -= INT_MAX;
6459 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006460 }
6461#endif
6462
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006463 return repr;
6464}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006465
Alexander Belopolsky40018472011-02-26 01:02:56 +00006466PyObject *
6467PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006468{
6469 if (!PyUnicode_Check(unicode)) {
6470 PyErr_BadArgument();
6471 return NULL;
6472 }
6473 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 PyUnicode_GET_SIZE(unicode),
6475 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006476}
6477
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006478#undef NEED_RETRY
6479
Victor Stinner99b95382011-07-04 14:23:54 +02006480#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006481
Guido van Rossumd57fd912000-03-10 22:53:23 +00006482/* --- Character Mapping Codec -------------------------------------------- */
6483
Alexander Belopolsky40018472011-02-26 01:02:56 +00006484PyObject *
6485PyUnicode_DecodeCharmap(const char *s,
6486 Py_ssize_t size,
6487 PyObject *mapping,
6488 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006489{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006490 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006491 Py_ssize_t startinpos;
6492 Py_ssize_t endinpos;
6493 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006495 PyUnicodeObject *v;
6496 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006497 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006498 PyObject *errorHandler = NULL;
6499 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006500 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006501 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006502
Guido van Rossumd57fd912000-03-10 22:53:23 +00006503 /* Default to Latin-1 */
6504 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006506
6507 v = _PyUnicode_New(size);
6508 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006513 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006514 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 mapstring = PyUnicode_AS_UNICODE(mapping);
6516 maplen = PyUnicode_GET_SIZE(mapping);
6517 while (s < e) {
6518 unsigned char ch = *s;
6519 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006520
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 if (ch < maplen)
6522 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006523
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 if (x == 0xfffe) {
6525 /* undefined mapping */
6526 outpos = p-PyUnicode_AS_UNICODE(v);
6527 startinpos = s-starts;
6528 endinpos = startinpos+1;
6529 if (unicode_decode_call_errorhandler(
6530 errors, &errorHandler,
6531 "charmap", "character maps to <undefined>",
6532 &starts, &e, &startinpos, &endinpos, &exc, &s,
6533 &v, &outpos, &p)) {
6534 goto onError;
6535 }
6536 continue;
6537 }
6538 *p++ = x;
6539 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006540 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006541 }
6542 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 while (s < e) {
6544 unsigned char ch = *s;
6545 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006546
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 /* Get mapping (char ordinal -> integer, Unicode char or None) */
6548 w = PyLong_FromLong((long)ch);
6549 if (w == NULL)
6550 goto onError;
6551 x = PyObject_GetItem(mapping, w);
6552 Py_DECREF(w);
6553 if (x == NULL) {
6554 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6555 /* No mapping found means: mapping is undefined. */
6556 PyErr_Clear();
6557 x = Py_None;
6558 Py_INCREF(x);
6559 } else
6560 goto onError;
6561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006562
Benjamin Peterson29060642009-01-31 22:14:21 +00006563 /* Apply mapping */
6564 if (PyLong_Check(x)) {
6565 long value = PyLong_AS_LONG(x);
6566 if (value < 0 || value > 65535) {
6567 PyErr_SetString(PyExc_TypeError,
6568 "character mapping must be in range(65536)");
6569 Py_DECREF(x);
6570 goto onError;
6571 }
6572 *p++ = (Py_UNICODE)value;
6573 }
6574 else if (x == Py_None) {
6575 /* undefined mapping */
6576 outpos = p-PyUnicode_AS_UNICODE(v);
6577 startinpos = s-starts;
6578 endinpos = startinpos+1;
6579 if (unicode_decode_call_errorhandler(
6580 errors, &errorHandler,
6581 "charmap", "character maps to <undefined>",
6582 &starts, &e, &startinpos, &endinpos, &exc, &s,
6583 &v, &outpos, &p)) {
6584 Py_DECREF(x);
6585 goto onError;
6586 }
6587 Py_DECREF(x);
6588 continue;
6589 }
6590 else if (PyUnicode_Check(x)) {
6591 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006592
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 if (targetsize == 1)
6594 /* 1-1 mapping */
6595 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006596
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 else if (targetsize > 1) {
6598 /* 1-n mapping */
6599 if (targetsize > extrachars) {
6600 /* resize first */
6601 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
6602 Py_ssize_t needed = (targetsize - extrachars) + \
6603 (targetsize << 2);
6604 extrachars += needed;
6605 /* XXX overflow detection missing */
6606 if (_PyUnicode_Resize(&v,
6607 PyUnicode_GET_SIZE(v) + needed) < 0) {
6608 Py_DECREF(x);
6609 goto onError;
6610 }
6611 p = PyUnicode_AS_UNICODE(v) + oldpos;
6612 }
6613 Py_UNICODE_COPY(p,
6614 PyUnicode_AS_UNICODE(x),
6615 targetsize);
6616 p += targetsize;
6617 extrachars -= targetsize;
6618 }
6619 /* 1-0 mapping: skip the character */
6620 }
6621 else {
6622 /* wrong return value */
6623 PyErr_SetString(PyExc_TypeError,
6624 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006625 Py_DECREF(x);
6626 goto onError;
6627 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 Py_DECREF(x);
6629 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006630 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006631 }
6632 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Benjamin Peterson29060642009-01-31 22:14:21 +00006633 if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
6634 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635 Py_XDECREF(errorHandler);
6636 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006637 if (PyUnicode_READY(v) == -1) {
6638 Py_DECREF(v);
6639 return NULL;
6640 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006642
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 Py_XDECREF(errorHandler);
6645 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006646 Py_XDECREF(v);
6647 return NULL;
6648}
6649
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006650/* Charmap encoding: the lookup table */
6651
Alexander Belopolsky40018472011-02-26 01:02:56 +00006652struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 PyObject_HEAD
6654 unsigned char level1[32];
6655 int count2, count3;
6656 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006657};
6658
6659static PyObject*
6660encoding_map_size(PyObject *obj, PyObject* args)
6661{
6662 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006663 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006665}
6666
6667static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006668 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00006669 PyDoc_STR("Return the size (in bytes) of this object") },
6670 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006671};
6672
6673static void
6674encoding_map_dealloc(PyObject* o)
6675{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006676 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006677}
6678
6679static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006680 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 "EncodingMap", /*tp_name*/
6682 sizeof(struct encoding_map), /*tp_basicsize*/
6683 0, /*tp_itemsize*/
6684 /* methods */
6685 encoding_map_dealloc, /*tp_dealloc*/
6686 0, /*tp_print*/
6687 0, /*tp_getattr*/
6688 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00006689 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00006690 0, /*tp_repr*/
6691 0, /*tp_as_number*/
6692 0, /*tp_as_sequence*/
6693 0, /*tp_as_mapping*/
6694 0, /*tp_hash*/
6695 0, /*tp_call*/
6696 0, /*tp_str*/
6697 0, /*tp_getattro*/
6698 0, /*tp_setattro*/
6699 0, /*tp_as_buffer*/
6700 Py_TPFLAGS_DEFAULT, /*tp_flags*/
6701 0, /*tp_doc*/
6702 0, /*tp_traverse*/
6703 0, /*tp_clear*/
6704 0, /*tp_richcompare*/
6705 0, /*tp_weaklistoffset*/
6706 0, /*tp_iter*/
6707 0, /*tp_iternext*/
6708 encoding_map_methods, /*tp_methods*/
6709 0, /*tp_members*/
6710 0, /*tp_getset*/
6711 0, /*tp_base*/
6712 0, /*tp_dict*/
6713 0, /*tp_descr_get*/
6714 0, /*tp_descr_set*/
6715 0, /*tp_dictoffset*/
6716 0, /*tp_init*/
6717 0, /*tp_alloc*/
6718 0, /*tp_new*/
6719 0, /*tp_free*/
6720 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006721};
6722
6723PyObject*
6724PyUnicode_BuildEncodingMap(PyObject* string)
6725{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006726 PyObject *result;
6727 struct encoding_map *mresult;
6728 int i;
6729 int need_dict = 0;
6730 unsigned char level1[32];
6731 unsigned char level2[512];
6732 unsigned char *mlevel1, *mlevel2, *mlevel3;
6733 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006734 int kind;
6735 void *data;
6736 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006737
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006738 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006739 PyErr_BadArgument();
6740 return NULL;
6741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006742 kind = PyUnicode_KIND(string);
6743 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006744 memset(level1, 0xFF, sizeof level1);
6745 memset(level2, 0xFF, sizeof level2);
6746
6747 /* If there isn't a one-to-one mapping of NULL to \0,
6748 or if there are non-BMP characters, we need to use
6749 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006750 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006751 need_dict = 1;
6752 for (i = 1; i < 256; i++) {
6753 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006754 ch = PyUnicode_READ(kind, data, i);
6755 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006756 need_dict = 1;
6757 break;
6758 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006759 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006760 /* unmapped character */
6761 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006762 l1 = ch >> 11;
6763 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006764 if (level1[l1] == 0xFF)
6765 level1[l1] = count2++;
6766 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00006767 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006768 }
6769
6770 if (count2 >= 0xFF || count3 >= 0xFF)
6771 need_dict = 1;
6772
6773 if (need_dict) {
6774 PyObject *result = PyDict_New();
6775 PyObject *key, *value;
6776 if (!result)
6777 return NULL;
6778 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006779 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00006780 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006781 if (!key || !value)
6782 goto failed1;
6783 if (PyDict_SetItem(result, key, value) == -1)
6784 goto failed1;
6785 Py_DECREF(key);
6786 Py_DECREF(value);
6787 }
6788 return result;
6789 failed1:
6790 Py_XDECREF(key);
6791 Py_XDECREF(value);
6792 Py_DECREF(result);
6793 return NULL;
6794 }
6795
6796 /* Create a three-level trie */
6797 result = PyObject_MALLOC(sizeof(struct encoding_map) +
6798 16*count2 + 128*count3 - 1);
6799 if (!result)
6800 return PyErr_NoMemory();
6801 PyObject_Init(result, &EncodingMapType);
6802 mresult = (struct encoding_map*)result;
6803 mresult->count2 = count2;
6804 mresult->count3 = count3;
6805 mlevel1 = mresult->level1;
6806 mlevel2 = mresult->level23;
6807 mlevel3 = mresult->level23 + 16*count2;
6808 memcpy(mlevel1, level1, 32);
6809 memset(mlevel2, 0xFF, 16*count2);
6810 memset(mlevel3, 0, 128*count3);
6811 count3 = 0;
6812 for (i = 1; i < 256; i++) {
6813 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006815 /* unmapped character */
6816 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006817 o1 = PyUnicode_READ(kind, data, i)>>11;
6818 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006819 i2 = 16*mlevel1[o1] + o2;
6820 if (mlevel2[i2] == 0xFF)
6821 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006822 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006823 i3 = 128*mlevel2[i2] + o3;
6824 mlevel3[i3] = i;
6825 }
6826 return result;
6827}
6828
6829static int
6830encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
6831{
6832 struct encoding_map *map = (struct encoding_map*)mapping;
6833 int l1 = c>>11;
6834 int l2 = (c>>7) & 0xF;
6835 int l3 = c & 0x7F;
6836 int i;
6837
6838#ifdef Py_UNICODE_WIDE
6839 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006840 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006841 }
6842#endif
6843 if (c == 0)
6844 return 0;
6845 /* level 1*/
6846 i = map->level1[l1];
6847 if (i == 0xFF) {
6848 return -1;
6849 }
6850 /* level 2*/
6851 i = map->level23[16*i+l2];
6852 if (i == 0xFF) {
6853 return -1;
6854 }
6855 /* level 3 */
6856 i = map->level23[16*map->count2 + 128*i + l3];
6857 if (i == 0) {
6858 return -1;
6859 }
6860 return i;
6861}
6862
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006863/* Lookup the character ch in the mapping. If the character
6864 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00006865 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006866static PyObject *
6867charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006868{
Christian Heimes217cfd12007-12-02 14:31:20 +00006869 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006870 PyObject *x;
6871
6872 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006873 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006874 x = PyObject_GetItem(mapping, w);
6875 Py_DECREF(w);
6876 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006877 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6878 /* No mapping found means: mapping is undefined. */
6879 PyErr_Clear();
6880 x = Py_None;
6881 Py_INCREF(x);
6882 return x;
6883 } else
6884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006885 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00006886 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00006888 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006889 long value = PyLong_AS_LONG(x);
6890 if (value < 0 || value > 255) {
6891 PyErr_SetString(PyExc_TypeError,
6892 "character mapping must be in range(256)");
6893 Py_DECREF(x);
6894 return NULL;
6895 }
6896 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006897 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006898 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00006899 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006900 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 /* wrong return value */
6902 PyErr_Format(PyExc_TypeError,
6903 "character mapping must return integer, bytes or None, not %.400s",
6904 x->ob_type->tp_name);
6905 Py_DECREF(x);
6906 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006907 }
6908}
6909
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006910static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00006911charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006912{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006913 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
6914 /* exponentially overallocate to minimize reallocations */
6915 if (requiredsize < 2*outsize)
6916 requiredsize = 2*outsize;
6917 if (_PyBytes_Resize(outobj, requiredsize))
6918 return -1;
6919 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006920}
6921
Benjamin Peterson14339b62009-01-31 16:36:08 +00006922typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00006923 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00006924} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00006926 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927 space is available. Return a new reference to the object that
6928 was put in the output buffer, or Py_None, if the mapping was undefined
6929 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00006930 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006931static charmapencode_result
6932charmapencode_output(Py_UNICODE c, PyObject *mapping,
6933 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006934{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006935 PyObject *rep;
6936 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00006937 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006938
Christian Heimes90aa7642007-12-19 02:45:37 +00006939 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006940 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006942 if (res == -1)
6943 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 if (outsize<requiredsize)
6945 if (charmapencode_resize(outobj, outpos, requiredsize))
6946 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00006947 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006948 outstart[(*outpos)++] = (char)res;
6949 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006950 }
6951
6952 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006953 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006954 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006955 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006956 Py_DECREF(rep);
6957 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006958 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 if (PyLong_Check(rep)) {
6960 Py_ssize_t requiredsize = *outpos+1;
6961 if (outsize<requiredsize)
6962 if (charmapencode_resize(outobj, outpos, requiredsize)) {
6963 Py_DECREF(rep);
6964 return enc_EXCEPTION;
6965 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006966 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006967 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006968 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006969 else {
6970 const char *repchars = PyBytes_AS_STRING(rep);
6971 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
6972 Py_ssize_t requiredsize = *outpos+repsize;
6973 if (outsize<requiredsize)
6974 if (charmapencode_resize(outobj, outpos, requiredsize)) {
6975 Py_DECREF(rep);
6976 return enc_EXCEPTION;
6977 }
Christian Heimes72b710a2008-05-26 13:28:38 +00006978 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 memcpy(outstart + *outpos, repchars, repsize);
6980 *outpos += repsize;
6981 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006982 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006983 Py_DECREF(rep);
6984 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006985}
6986
6987/* handle an error in PyUnicode_EncodeCharmap
6988 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006989static int
6990charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00006991 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006992 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00006993 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00006994 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006995{
6996 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006997 Py_ssize_t repsize;
6998 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006999 Py_UNICODE *uni2;
7000 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007001 Py_ssize_t collstartpos = *inpos;
7002 Py_ssize_t collendpos = *inpos+1;
7003 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007004 char *encoding = "charmap";
7005 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007006 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007007
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007008 /* find all unencodable characters */
7009 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007010 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007011 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007012 int res = encoding_map_lookup(p[collendpos], mapping);
7013 if (res != -1)
7014 break;
7015 ++collendpos;
7016 continue;
7017 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007018
Benjamin Peterson29060642009-01-31 22:14:21 +00007019 rep = charmapencode_lookup(p[collendpos], mapping);
7020 if (rep==NULL)
7021 return -1;
7022 else if (rep!=Py_None) {
7023 Py_DECREF(rep);
7024 break;
7025 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007026 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007027 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007028 }
7029 /* cache callback name lookup
7030 * (if not done yet, i.e. it's the first error) */
7031 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007032 if ((errors==NULL) || (!strcmp(errors, "strict")))
7033 *known_errorHandler = 1;
7034 else if (!strcmp(errors, "replace"))
7035 *known_errorHandler = 2;
7036 else if (!strcmp(errors, "ignore"))
7037 *known_errorHandler = 3;
7038 else if (!strcmp(errors, "xmlcharrefreplace"))
7039 *known_errorHandler = 4;
7040 else
7041 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007042 }
7043 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007044 case 1: /* strict */
7045 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7046 return -1;
7047 case 2: /* replace */
7048 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007049 x = charmapencode_output('?', mapping, res, respos);
7050 if (x==enc_EXCEPTION) {
7051 return -1;
7052 }
7053 else if (x==enc_FAILED) {
7054 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7055 return -1;
7056 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007057 }
7058 /* fall through */
7059 case 3: /* ignore */
7060 *inpos = collendpos;
7061 break;
7062 case 4: /* xmlcharrefreplace */
7063 /* generate replacement (temporarily (mis)uses p) */
7064 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007065 char buffer[2+29+1+1];
7066 char *cp;
7067 sprintf(buffer, "&#%d;", (int)p[collpos]);
7068 for (cp = buffer; *cp; ++cp) {
7069 x = charmapencode_output(*cp, mapping, res, respos);
7070 if (x==enc_EXCEPTION)
7071 return -1;
7072 else if (x==enc_FAILED) {
7073 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7074 return -1;
7075 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007076 }
7077 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007078 *inpos = collendpos;
7079 break;
7080 default:
7081 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007082 encoding, reason, p, size, exceptionObject,
7083 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007084 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007085 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007086 if (PyBytes_Check(repunicode)) {
7087 /* Directly copy bytes result to output. */
7088 Py_ssize_t outsize = PyBytes_Size(*res);
7089 Py_ssize_t requiredsize;
7090 repsize = PyBytes_Size(repunicode);
7091 requiredsize = *respos + repsize;
7092 if (requiredsize > outsize)
7093 /* Make room for all additional bytes. */
7094 if (charmapencode_resize(res, respos, requiredsize)) {
7095 Py_DECREF(repunicode);
7096 return -1;
7097 }
7098 memcpy(PyBytes_AsString(*res) + *respos,
7099 PyBytes_AsString(repunicode), repsize);
7100 *respos += repsize;
7101 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007102 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007103 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007104 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007105 /* generate replacement */
7106 repsize = PyUnicode_GET_SIZE(repunicode);
7107 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007108 x = charmapencode_output(*uni2, mapping, res, respos);
7109 if (x==enc_EXCEPTION) {
7110 return -1;
7111 }
7112 else if (x==enc_FAILED) {
7113 Py_DECREF(repunicode);
7114 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7115 return -1;
7116 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007117 }
7118 *inpos = newpos;
7119 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007120 }
7121 return 0;
7122}
7123
Alexander Belopolsky40018472011-02-26 01:02:56 +00007124PyObject *
7125PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7126 Py_ssize_t size,
7127 PyObject *mapping,
7128 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007129{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007130 /* output object */
7131 PyObject *res = NULL;
7132 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007133 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007134 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007135 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007136 PyObject *errorHandler = NULL;
7137 PyObject *exc = NULL;
7138 /* the following variable is used for caching string comparisons
7139 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7140 * 3=ignore, 4=xmlcharrefreplace */
7141 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007142
7143 /* Default to Latin-1 */
7144 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007145 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007147 /* allocate enough for a simple encoding without
7148 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007149 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007150 if (res == NULL)
7151 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007152 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007153 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007154
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007155 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007156 /* try to encode it */
7157 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7158 if (x==enc_EXCEPTION) /* error */
7159 goto onError;
7160 if (x==enc_FAILED) { /* unencodable character */
7161 if (charmap_encoding_error(p, size, &inpos, mapping,
7162 &exc,
7163 &known_errorHandler, &errorHandler, errors,
7164 &res, &respos)) {
7165 goto onError;
7166 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007167 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007168 else
7169 /* done with this character => adjust input position */
7170 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007171 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007172
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007173 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007174 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007175 if (_PyBytes_Resize(&res, respos) < 0)
7176 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007177
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007178 Py_XDECREF(exc);
7179 Py_XDECREF(errorHandler);
7180 return res;
7181
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007183 Py_XDECREF(res);
7184 Py_XDECREF(exc);
7185 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007186 return NULL;
7187}
7188
Alexander Belopolsky40018472011-02-26 01:02:56 +00007189PyObject *
7190PyUnicode_AsCharmapString(PyObject *unicode,
7191 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007192{
7193 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007194 PyErr_BadArgument();
7195 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007196 }
7197 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 PyUnicode_GET_SIZE(unicode),
7199 mapping,
7200 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007201}
7202
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007203/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007204static void
7205make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007206 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007207 Py_ssize_t startpos, Py_ssize_t endpos,
7208 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007209{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007210 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007211 *exceptionObject = _PyUnicodeTranslateError_Create(
7212 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007213 }
7214 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007215 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7216 goto onError;
7217 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7218 goto onError;
7219 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7220 goto onError;
7221 return;
7222 onError:
7223 Py_DECREF(*exceptionObject);
7224 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007225 }
7226}
7227
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007228/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007229static void
7230raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007231 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007232 Py_ssize_t startpos, Py_ssize_t endpos,
7233 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007234{
7235 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007236 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007237 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007238 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007239}
7240
7241/* error handling callback helper:
7242 build arguments, call the callback and check the arguments,
7243 put the result into newpos and return the replacement string, which
7244 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007245static PyObject *
7246unicode_translate_call_errorhandler(const char *errors,
7247 PyObject **errorHandler,
7248 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007249 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007250 Py_ssize_t startpos, Py_ssize_t endpos,
7251 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007252{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007253 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007254
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007255 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007256 PyObject *restuple;
7257 PyObject *resunicode;
7258
7259 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007261 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007262 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007263 }
7264
7265 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007266 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007267 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007268 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007269
7270 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007271 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007272 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007273 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007274 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007275 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007276 Py_DECREF(restuple);
7277 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007278 }
7279 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007280 &resunicode, &i_newpos)) {
7281 Py_DECREF(restuple);
7282 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007283 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007284 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007285 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007286 else
7287 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007288 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007289 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7290 Py_DECREF(restuple);
7291 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007292 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007293 Py_INCREF(resunicode);
7294 Py_DECREF(restuple);
7295 return resunicode;
7296}
7297
7298/* Lookup the character ch in the mapping and put the result in result,
7299 which must be decrefed by the caller.
7300 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007301static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007302charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007303{
Christian Heimes217cfd12007-12-02 14:31:20 +00007304 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007305 PyObject *x;
7306
7307 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007308 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007309 x = PyObject_GetItem(mapping, w);
7310 Py_DECREF(w);
7311 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007312 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7313 /* No mapping found means: use 1:1 mapping. */
7314 PyErr_Clear();
7315 *result = NULL;
7316 return 0;
7317 } else
7318 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007319 }
7320 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007321 *result = x;
7322 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007323 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007324 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007325 long value = PyLong_AS_LONG(x);
7326 long max = PyUnicode_GetMax();
7327 if (value < 0 || value > max) {
7328 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007329 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007330 Py_DECREF(x);
7331 return -1;
7332 }
7333 *result = x;
7334 return 0;
7335 }
7336 else if (PyUnicode_Check(x)) {
7337 *result = x;
7338 return 0;
7339 }
7340 else {
7341 /* wrong return value */
7342 PyErr_SetString(PyExc_TypeError,
7343 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007344 Py_DECREF(x);
7345 return -1;
7346 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007347}
7348/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007349 if not reallocate and adjust various state variables.
7350 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007351static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007352charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007353 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007354{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007355 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007356 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007357 /* exponentially overallocate to minimize reallocations */
7358 if (requiredsize < 2 * oldsize)
7359 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007360 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7361 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007362 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007363 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007364 }
7365 return 0;
7366}
7367/* lookup the character, put the result in the output string and adjust
7368 various state variables. Return a new reference to the object that
7369 was put in the output buffer in *result, or Py_None, if the mapping was
7370 undefined (in which case no character was written).
7371 The called must decref result.
7372 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007373static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007374charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
7375 PyObject *mapping, Py_UCS4 **output,
7376 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007377 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007378{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007379 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
7380 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00007381 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007382 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007383 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007384 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007385 }
7386 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007387 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00007388 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007389 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007390 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007391 }
7392 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007393 Py_ssize_t repsize;
7394 if (PyUnicode_READY(*res) == -1)
7395 return -1;
7396 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00007397 if (repsize==1) {
7398 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007399 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00007400 }
7401 else if (repsize!=0) {
7402 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007403 Py_ssize_t requiredsize = *opos +
7404 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00007405 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007406 Py_ssize_t i;
7407 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007408 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007409 for(i = 0; i < repsize; i++)
7410 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00007411 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007412 }
7413 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007414 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007415 return 0;
7416}
7417
Alexander Belopolsky40018472011-02-26 01:02:56 +00007418PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007419_PyUnicode_TranslateCharmap(PyObject *input,
7420 PyObject *mapping,
7421 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007422{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007423 /* input object */
7424 char *idata;
7425 Py_ssize_t size, i;
7426 int kind;
7427 /* output buffer */
7428 Py_UCS4 *output = NULL;
7429 Py_ssize_t osize;
7430 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007431 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007432 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007433 char *reason = "character maps to <undefined>";
7434 PyObject *errorHandler = NULL;
7435 PyObject *exc = NULL;
7436 /* the following variable is used for caching string comparisons
7437 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7438 * 3=ignore, 4=xmlcharrefreplace */
7439 int known_errorHandler = -1;
7440
Guido van Rossumd57fd912000-03-10 22:53:23 +00007441 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007442 PyErr_BadArgument();
7443 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007444 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007446 if (PyUnicode_READY(input) == -1)
7447 return NULL;
7448 idata = (char*)PyUnicode_DATA(input);
7449 kind = PyUnicode_KIND(input);
7450 size = PyUnicode_GET_LENGTH(input);
7451 i = 0;
7452
7453 if (size == 0) {
7454 Py_INCREF(input);
7455 return input;
7456 }
7457
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007458 /* allocate enough for a simple 1:1 translation without
7459 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007460 osize = size;
7461 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
7462 opos = 0;
7463 if (output == NULL) {
7464 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007465 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007468 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007469 /* try to encode it */
7470 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007471 if (charmaptranslate_output(input, i, mapping,
7472 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007473 Py_XDECREF(x);
7474 goto onError;
7475 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007476 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00007477 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007478 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00007479 else { /* untranslatable character */
7480 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
7481 Py_ssize_t repsize;
7482 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007483 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007485 Py_ssize_t collstart = i;
7486 Py_ssize_t collend = i+1;
7487 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007488
Benjamin Peterson29060642009-01-31 22:14:21 +00007489 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007490 while (collend < size) {
7491 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007492 goto onError;
7493 Py_XDECREF(x);
7494 if (x!=Py_None)
7495 break;
7496 ++collend;
7497 }
7498 /* cache callback name lookup
7499 * (if not done yet, i.e. it's the first error) */
7500 if (known_errorHandler==-1) {
7501 if ((errors==NULL) || (!strcmp(errors, "strict")))
7502 known_errorHandler = 1;
7503 else if (!strcmp(errors, "replace"))
7504 known_errorHandler = 2;
7505 else if (!strcmp(errors, "ignore"))
7506 known_errorHandler = 3;
7507 else if (!strcmp(errors, "xmlcharrefreplace"))
7508 known_errorHandler = 4;
7509 else
7510 known_errorHandler = 0;
7511 }
7512 switch (known_errorHandler) {
7513 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007514 raise_translate_exception(&exc, input, collstart,
7515 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007516 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007517 case 2: /* replace */
7518 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007519 for (coll = collstart; coll<collend; coll++)
7520 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 /* fall through */
7522 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007523 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007524 break;
7525 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007526 /* generate replacement (temporarily (mis)uses i) */
7527 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007528 char buffer[2+29+1+1];
7529 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007530 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
7531 if (charmaptranslate_makespace(&output, &osize,
7532 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007533 goto onError;
7534 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007535 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00007536 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007537 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007538 break;
7539 default:
7540 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007541 reason, input, &exc,
7542 collstart, collend, &newpos);
7543 if (repunicode == NULL || PyUnicode_READY(repunicode) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 goto onError;
7545 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007546 repsize = PyUnicode_GET_LENGTH(repunicode);
7547 if (charmaptranslate_makespace(&output, &osize,
7548 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007549 Py_DECREF(repunicode);
7550 goto onError;
7551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007552 for (uni2 = 0; repsize-->0; ++uni2)
7553 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
7554 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007556 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007557 }
7558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007559 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
7560 if (!res)
7561 goto onError;
7562 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007563 Py_XDECREF(exc);
7564 Py_XDECREF(errorHandler);
7565 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007568 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007569 Py_XDECREF(exc);
7570 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571 return NULL;
7572}
7573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007574/* Deprecated. Use PyUnicode_Translate instead. */
7575PyObject *
7576PyUnicode_TranslateCharmap(const Py_UNICODE *p,
7577 Py_ssize_t size,
7578 PyObject *mapping,
7579 const char *errors)
7580{
7581 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7582 if (!unicode)
7583 return NULL;
7584 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
7585}
7586
Alexander Belopolsky40018472011-02-26 01:02:56 +00007587PyObject *
7588PyUnicode_Translate(PyObject *str,
7589 PyObject *mapping,
7590 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007591{
7592 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00007593
Guido van Rossumd57fd912000-03-10 22:53:23 +00007594 str = PyUnicode_FromObject(str);
7595 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007597 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007598 Py_DECREF(str);
7599 return result;
Tim Petersced69f82003-09-16 20:30:58 +00007600
Benjamin Peterson29060642009-01-31 22:14:21 +00007601 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007602 Py_XDECREF(str);
7603 return NULL;
7604}
Tim Petersced69f82003-09-16 20:30:58 +00007605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007606static Py_UCS4
7607fix_decimal_and_space_to_ascii(PyUnicodeObject *self)
7608{
7609 /* No need to call PyUnicode_READY(self) because this function is only
7610 called as a callback from fixup() which does it already. */
7611 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
7612 const int kind = PyUnicode_KIND(self);
7613 void *data = PyUnicode_DATA(self);
7614 Py_UCS4 maxchar = 0, ch, fixed;
7615 Py_ssize_t i;
7616
7617 for (i = 0; i < len; ++i) {
7618 ch = PyUnicode_READ(kind, data, i);
7619 fixed = 0;
7620 if (ch > 127) {
7621 if (Py_UNICODE_ISSPACE(ch))
7622 fixed = ' ';
7623 else {
7624 const int decimal = Py_UNICODE_TODECIMAL(ch);
7625 if (decimal >= 0)
7626 fixed = '0' + decimal;
7627 }
7628 if (fixed != 0) {
7629 if (fixed > maxchar)
7630 maxchar = fixed;
7631 PyUnicode_WRITE(kind, data, i, fixed);
7632 }
7633 else if (ch > maxchar)
7634 maxchar = ch;
7635 }
7636 else if (ch > maxchar)
7637 maxchar = ch;
7638 }
7639
7640 return maxchar;
7641}
7642
7643PyObject *
7644_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
7645{
7646 if (!PyUnicode_Check(unicode)) {
7647 PyErr_BadInternalCall();
7648 return NULL;
7649 }
7650 if (PyUnicode_READY(unicode) == -1)
7651 return NULL;
7652 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
7653 /* If the string is already ASCII, just return the same string */
7654 Py_INCREF(unicode);
7655 return unicode;
7656 }
7657 return fixup((PyUnicodeObject *)unicode, fix_decimal_and_space_to_ascii);
7658}
7659
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007660PyObject *
7661PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
7662 Py_ssize_t length)
7663{
7664 PyObject *result;
7665 Py_UNICODE *p; /* write pointer into result */
7666 Py_ssize_t i;
7667 /* Copy to a new string */
7668 result = (PyObject *)_PyUnicode_New(length);
7669 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
7670 if (result == NULL)
7671 return result;
7672 p = PyUnicode_AS_UNICODE(result);
7673 /* Iterate over code points */
7674 for (i = 0; i < length; i++) {
7675 Py_UNICODE ch =s[i];
7676 if (ch > 127) {
7677 int decimal = Py_UNICODE_TODECIMAL(ch);
7678 if (decimal >= 0)
7679 p[i] = '0' + decimal;
7680 }
7681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007682 if (PyUnicode_READY((PyUnicodeObject*)result) == -1) {
7683 Py_DECREF(result);
7684 return NULL;
7685 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007686 return result;
7687}
Guido van Rossum9e896b32000-04-05 20:11:21 +00007688/* --- Decimal Encoder ---------------------------------------------------- */
7689
Alexander Belopolsky40018472011-02-26 01:02:56 +00007690int
7691PyUnicode_EncodeDecimal(Py_UNICODE *s,
7692 Py_ssize_t length,
7693 char *output,
7694 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00007695{
7696 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007697 PyObject *errorHandler = NULL;
7698 PyObject *exc = NULL;
7699 const char *encoding = "decimal";
7700 const char *reason = "invalid decimal Unicode string";
7701 /* the following variable is used for caching string comparisons
7702 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
7703 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007704
7705 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 PyErr_BadArgument();
7707 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007708 }
7709
7710 p = s;
7711 end = s + length;
7712 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007713 register Py_UNICODE ch = *p;
7714 int decimal;
7715 PyObject *repunicode;
7716 Py_ssize_t repsize;
7717 Py_ssize_t newpos;
7718 Py_UNICODE *uni2;
7719 Py_UNICODE *collstart;
7720 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00007721
Benjamin Peterson29060642009-01-31 22:14:21 +00007722 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007723 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00007724 ++p;
7725 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007726 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 decimal = Py_UNICODE_TODECIMAL(ch);
7728 if (decimal >= 0) {
7729 *output++ = '0' + decimal;
7730 ++p;
7731 continue;
7732 }
7733 if (0 < ch && ch < 256) {
7734 *output++ = (char)ch;
7735 ++p;
7736 continue;
7737 }
7738 /* All other characters are considered unencodable */
7739 collstart = p;
7740 collend = p+1;
7741 while (collend < end) {
7742 if ((0 < *collend && *collend < 256) ||
7743 !Py_UNICODE_ISSPACE(*collend) ||
7744 Py_UNICODE_TODECIMAL(*collend))
7745 break;
7746 }
7747 /* cache callback name lookup
7748 * (if not done yet, i.e. it's the first error) */
7749 if (known_errorHandler==-1) {
7750 if ((errors==NULL) || (!strcmp(errors, "strict")))
7751 known_errorHandler = 1;
7752 else if (!strcmp(errors, "replace"))
7753 known_errorHandler = 2;
7754 else if (!strcmp(errors, "ignore"))
7755 known_errorHandler = 3;
7756 else if (!strcmp(errors, "xmlcharrefreplace"))
7757 known_errorHandler = 4;
7758 else
7759 known_errorHandler = 0;
7760 }
7761 switch (known_errorHandler) {
7762 case 1: /* strict */
7763 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
7764 goto onError;
7765 case 2: /* replace */
7766 for (p = collstart; p < collend; ++p)
7767 *output++ = '?';
7768 /* fall through */
7769 case 3: /* ignore */
7770 p = collend;
7771 break;
7772 case 4: /* xmlcharrefreplace */
7773 /* generate replacement (temporarily (mis)uses p) */
7774 for (p = collstart; p < collend; ++p)
7775 output += sprintf(output, "&#%d;", (int)*p);
7776 p = collend;
7777 break;
7778 default:
7779 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
7780 encoding, reason, s, length, &exc,
7781 collstart-s, collend-s, &newpos);
7782 if (repunicode == NULL)
7783 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007784 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00007785 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007786 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
7787 Py_DECREF(repunicode);
7788 goto onError;
7789 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 /* generate replacement */
7791 repsize = PyUnicode_GET_SIZE(repunicode);
7792 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
7793 Py_UNICODE ch = *uni2;
7794 if (Py_UNICODE_ISSPACE(ch))
7795 *output++ = ' ';
7796 else {
7797 decimal = Py_UNICODE_TODECIMAL(ch);
7798 if (decimal >= 0)
7799 *output++ = '0' + decimal;
7800 else if (0 < ch && ch < 256)
7801 *output++ = (char)ch;
7802 else {
7803 Py_DECREF(repunicode);
7804 raise_encode_exception(&exc, encoding,
7805 s, length, collstart-s, collend-s, reason);
7806 goto onError;
7807 }
7808 }
7809 }
7810 p = s + newpos;
7811 Py_DECREF(repunicode);
7812 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00007813 }
7814 /* 0-terminate the output string */
7815 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 Py_XDECREF(exc);
7817 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00007818 return 0;
7819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007821 Py_XDECREF(exc);
7822 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00007823 return -1;
7824}
7825
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826/* --- Helpers ------------------------------------------------------------ */
7827
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007828#include "stringlib/ucs1lib.h"
7829#include "stringlib/fastsearch.h"
7830#include "stringlib/partition.h"
7831#include "stringlib/split.h"
7832#include "stringlib/count.h"
7833#include "stringlib/find.h"
7834#include "stringlib/localeutil.h"
7835#include "stringlib/undef.h"
7836
7837#include "stringlib/ucs2lib.h"
7838#include "stringlib/fastsearch.h"
7839#include "stringlib/partition.h"
7840#include "stringlib/split.h"
7841#include "stringlib/count.h"
7842#include "stringlib/find.h"
7843#include "stringlib/localeutil.h"
7844#include "stringlib/undef.h"
7845
7846#include "stringlib/ucs4lib.h"
7847#include "stringlib/fastsearch.h"
7848#include "stringlib/partition.h"
7849#include "stringlib/split.h"
7850#include "stringlib/count.h"
7851#include "stringlib/find.h"
7852#include "stringlib/localeutil.h"
7853#include "stringlib/undef.h"
7854
7855static Py_ssize_t
7856any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
7857 const Py_UCS1*, Py_ssize_t,
7858 Py_ssize_t, Py_ssize_t),
7859 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
7860 const Py_UCS2*, Py_ssize_t,
7861 Py_ssize_t, Py_ssize_t),
7862 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
7863 const Py_UCS4*, Py_ssize_t,
7864 Py_ssize_t, Py_ssize_t),
7865 PyObject* s1, PyObject* s2,
7866 Py_ssize_t start,
7867 Py_ssize_t end)
7868{
7869 int kind1, kind2, kind;
7870 void *buf1, *buf2;
7871 Py_ssize_t len1, len2, result;
7872
7873 kind1 = PyUnicode_KIND(s1);
7874 kind2 = PyUnicode_KIND(s2);
7875 kind = kind1 > kind2 ? kind1 : kind2;
7876 buf1 = PyUnicode_DATA(s1);
7877 buf2 = PyUnicode_DATA(s2);
7878 if (kind1 != kind)
7879 buf1 = _PyUnicode_AsKind(s1, kind);
7880 if (!buf1)
7881 return -2;
7882 if (kind2 != kind)
7883 buf2 = _PyUnicode_AsKind(s2, kind);
7884 if (!buf2) {
7885 if (kind1 != kind) PyMem_Free(buf1);
7886 return -2;
7887 }
7888 len1 = PyUnicode_GET_LENGTH(s1);
7889 len2 = PyUnicode_GET_LENGTH(s2);
7890
7891 switch(kind) {
7892 case PyUnicode_1BYTE_KIND:
7893 result = ucs1(buf1, len1, buf2, len2, start, end);
7894 break;
7895 case PyUnicode_2BYTE_KIND:
7896 result = ucs2(buf1, len1, buf2, len2, start, end);
7897 break;
7898 case PyUnicode_4BYTE_KIND:
7899 result = ucs4(buf1, len1, buf2, len2, start, end);
7900 break;
7901 default:
7902 assert(0); result = -2;
7903 }
7904
7905 if (kind1 != kind)
7906 PyMem_Free(buf1);
7907 if (kind2 != kind)
7908 PyMem_Free(buf2);
7909
7910 return result;
7911}
7912
7913Py_ssize_t
7914_PyUnicode_InsertThousandsGrouping(int kind, void *data,
7915 Py_ssize_t n_buffer,
7916 void *digits, Py_ssize_t n_digits,
7917 Py_ssize_t min_width,
7918 const char *grouping,
7919 const char *thousands_sep)
7920{
7921 switch(kind) {
7922 case PyUnicode_1BYTE_KIND:
7923 return _PyUnicode_ucs1_InsertThousandsGrouping(
7924 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
7925 min_width, grouping, thousands_sep);
7926 case PyUnicode_2BYTE_KIND:
7927 return _PyUnicode_ucs2_InsertThousandsGrouping(
7928 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
7929 min_width, grouping, thousands_sep);
7930 case PyUnicode_4BYTE_KIND:
7931 return _PyUnicode_ucs4_InsertThousandsGrouping(
7932 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
7933 min_width, grouping, thousands_sep);
7934 }
7935 assert(0);
7936 return -1;
7937}
7938
7939
Eric Smith8c663262007-08-25 02:26:07 +00007940#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00007941#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007942
Thomas Wouters477c8d52006-05-27 19:21:47 +00007943#include "stringlib/count.h"
7944#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00007945
Thomas Wouters477c8d52006-05-27 19:21:47 +00007946/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00007947#define ADJUST_INDICES(start, end, len) \
7948 if (end > len) \
7949 end = len; \
7950 else if (end < 0) { \
7951 end += len; \
7952 if (end < 0) \
7953 end = 0; \
7954 } \
7955 if (start < 0) { \
7956 start += len; \
7957 if (start < 0) \
7958 start = 0; \
7959 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00007960
Alexander Belopolsky40018472011-02-26 01:02:56 +00007961Py_ssize_t
7962PyUnicode_Count(PyObject *str,
7963 PyObject *substr,
7964 Py_ssize_t start,
7965 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007966{
Martin v. Löwis18e16552006-02-15 17:27:45 +00007967 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007968 PyUnicodeObject* str_obj;
7969 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007970 int kind1, kind2, kind;
7971 void *buf1 = NULL, *buf2 = NULL;
7972 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00007973
Thomas Wouters477c8d52006-05-27 19:21:47 +00007974 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007975 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007976 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00007977 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02007978 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 Py_DECREF(str_obj);
7980 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981 }
Tim Petersced69f82003-09-16 20:30:58 +00007982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007983 kind1 = PyUnicode_KIND(str_obj);
7984 kind2 = PyUnicode_KIND(sub_obj);
7985 kind = kind1 > kind2 ? kind1 : kind2;
7986 buf1 = PyUnicode_DATA(str_obj);
7987 if (kind1 != kind)
7988 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
7989 if (!buf1)
7990 goto onError;
7991 buf2 = PyUnicode_DATA(sub_obj);
7992 if (kind2 != kind)
7993 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
7994 if (!buf2)
7995 goto onError;
7996 len1 = PyUnicode_GET_LENGTH(str_obj);
7997 len2 = PyUnicode_GET_LENGTH(sub_obj);
7998
7999 ADJUST_INDICES(start, end, len1);
8000 switch(kind) {
8001 case PyUnicode_1BYTE_KIND:
8002 result = ucs1lib_count(
8003 ((Py_UCS1*)buf1) + start, end - start,
8004 buf2, len2, PY_SSIZE_T_MAX
8005 );
8006 break;
8007 case PyUnicode_2BYTE_KIND:
8008 result = ucs2lib_count(
8009 ((Py_UCS2*)buf1) + start, end - start,
8010 buf2, len2, PY_SSIZE_T_MAX
8011 );
8012 break;
8013 case PyUnicode_4BYTE_KIND:
8014 result = ucs4lib_count(
8015 ((Py_UCS4*)buf1) + start, end - start,
8016 buf2, len2, PY_SSIZE_T_MAX
8017 );
8018 break;
8019 default:
8020 assert(0); result = 0;
8021 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008022
8023 Py_DECREF(sub_obj);
8024 Py_DECREF(str_obj);
8025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008026 if (kind1 != kind)
8027 PyMem_Free(buf1);
8028 if (kind2 != kind)
8029 PyMem_Free(buf2);
8030
Guido van Rossumd57fd912000-03-10 22:53:23 +00008031 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032 onError:
8033 Py_DECREF(sub_obj);
8034 Py_DECREF(str_obj);
8035 if (kind1 != kind && buf1)
8036 PyMem_Free(buf1);
8037 if (kind2 != kind && buf2)
8038 PyMem_Free(buf2);
8039 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008040}
8041
Alexander Belopolsky40018472011-02-26 01:02:56 +00008042Py_ssize_t
8043PyUnicode_Find(PyObject *str,
8044 PyObject *sub,
8045 Py_ssize_t start,
8046 Py_ssize_t end,
8047 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008048{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008049 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008050
Guido van Rossumd57fd912000-03-10 22:53:23 +00008051 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008052 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008054 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008055 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 Py_DECREF(str);
8057 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008058 }
Tim Petersced69f82003-09-16 20:30:58 +00008059
Thomas Wouters477c8d52006-05-27 19:21:47 +00008060 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008061 result = any_find_slice(
8062 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
8063 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008064 );
8065 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008066 result = any_find_slice(
8067 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
8068 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008069 );
8070
Guido van Rossumd57fd912000-03-10 22:53:23 +00008071 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008072 Py_DECREF(sub);
8073
Guido van Rossumd57fd912000-03-10 22:53:23 +00008074 return result;
8075}
8076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008077Py_ssize_t
8078PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8079 Py_ssize_t start, Py_ssize_t end,
8080 int direction)
8081{
8082 char *result;
8083 int kind;
8084 if (PyUnicode_READY(str) == -1)
8085 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008086 if (start < 0 || end < 0) {
8087 PyErr_SetString(PyExc_IndexError, "string index out of range");
8088 return -2;
8089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008090 if (end > PyUnicode_GET_LENGTH(str))
8091 end = PyUnicode_GET_LENGTH(str);
8092 kind = PyUnicode_KIND(str);
8093 result = findchar(PyUnicode_1BYTE_DATA(str)
8094 + PyUnicode_KIND_SIZE(kind, start),
8095 kind,
8096 end-start, ch, direction);
8097 if (!result)
8098 return -1;
8099 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8100}
8101
Alexander Belopolsky40018472011-02-26 01:02:56 +00008102static int
8103tailmatch(PyUnicodeObject *self,
8104 PyUnicodeObject *substring,
8105 Py_ssize_t start,
8106 Py_ssize_t end,
8107 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 int kind_self;
8110 int kind_sub;
8111 void *data_self;
8112 void *data_sub;
8113 Py_ssize_t offset;
8114 Py_ssize_t i;
8115 Py_ssize_t end_sub;
8116
8117 if (PyUnicode_READY(self) == -1 ||
8118 PyUnicode_READY(substring) == -1)
8119 return 0;
8120
8121 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008122 return 1;
8123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008124 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8125 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008129 kind_self = PyUnicode_KIND(self);
8130 data_self = PyUnicode_DATA(self);
8131 kind_sub = PyUnicode_KIND(substring);
8132 data_sub = PyUnicode_DATA(substring);
8133 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8134
8135 if (direction > 0)
8136 offset = end;
8137 else
8138 offset = start;
8139
8140 if (PyUnicode_READ(kind_self, data_self, offset) ==
8141 PyUnicode_READ(kind_sub, data_sub, 0) &&
8142 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8143 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8144 /* If both are of the same kind, memcmp is sufficient */
8145 if (kind_self == kind_sub) {
8146 return ! memcmp((char *)data_self +
8147 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8148 data_sub,
8149 PyUnicode_GET_LENGTH(substring) *
8150 PyUnicode_CHARACTER_SIZE(substring));
8151 }
8152 /* otherwise we have to compare each character by first accesing it */
8153 else {
8154 /* We do not need to compare 0 and len(substring)-1 because
8155 the if statement above ensured already that they are equal
8156 when we end up here. */
8157 // TODO: honor direction and do a forward or backwards search
8158 for (i = 1; i < end_sub; ++i) {
8159 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8160 PyUnicode_READ(kind_sub, data_sub, i))
8161 return 0;
8162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008164 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008165 }
8166
8167 return 0;
8168}
8169
Alexander Belopolsky40018472011-02-26 01:02:56 +00008170Py_ssize_t
8171PyUnicode_Tailmatch(PyObject *str,
8172 PyObject *substr,
8173 Py_ssize_t start,
8174 Py_ssize_t end,
8175 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008177 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008178
Guido van Rossumd57fd912000-03-10 22:53:23 +00008179 str = PyUnicode_FromObject(str);
8180 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008181 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008182 substr = PyUnicode_FromObject(substr);
8183 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 Py_DECREF(str);
8185 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186 }
Tim Petersced69f82003-09-16 20:30:58 +00008187
Guido van Rossumd57fd912000-03-10 22:53:23 +00008188 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 (PyUnicodeObject *)substr,
8190 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008191 Py_DECREF(str);
8192 Py_DECREF(substr);
8193 return result;
8194}
8195
Guido van Rossumd57fd912000-03-10 22:53:23 +00008196/* Apply fixfct filter to the Unicode object self and return a
8197 reference to the modified object */
8198
Alexander Belopolsky40018472011-02-26 01:02:56 +00008199static PyObject *
8200fixup(PyUnicodeObject *self,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008201 Py_UCS4 (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008203 PyObject *u;
8204 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008206 if (PyUnicode_READY(self) == -1)
8207 return NULL;
8208 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8209 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8210 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008211 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008214 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8215 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217 /* fix functions return the new maximum character in a string,
8218 if the kind of the resulting unicode object does not change,
8219 everything is fine. Otherwise we need to change the string kind
8220 and re-run the fix function. */
8221 maxchar_new = fixfct((PyUnicodeObject*)u);
8222 if (maxchar_new == 0)
8223 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8224 else if (maxchar_new <= 127)
8225 maxchar_new = 127;
8226 else if (maxchar_new <= 255)
8227 maxchar_new = 255;
8228 else if (maxchar_new <= 65535)
8229 maxchar_new = 65535;
8230 else
8231 maxchar_new = 1114111; /* 0x10ffff */
8232
8233 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 /* fixfct should return TRUE if it modified the buffer. If
8235 FALSE, return a reference to the original buffer instead
8236 (to save space, not time) */
8237 Py_INCREF(self);
8238 Py_DECREF(u);
8239 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008241 else if (maxchar_new == maxchar_old) {
8242 return u;
8243 }
8244 else {
8245 /* In case the maximum character changed, we need to
8246 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008247 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008248 if (v == NULL) {
8249 Py_DECREF(u);
8250 return NULL;
8251 }
8252 if (maxchar_new > maxchar_old) {
8253 /* If the maxchar increased so that the kind changed, not all
8254 characters are representable anymore and we need to fix the
8255 string again. This only happens in very few cases. */
Victor Stinner157f83f2011-09-28 21:41:31 +02008256 if (PyUnicode_CopyCharacters(v, 0,
8257 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008258 PyUnicode_GET_LENGTH(self)) < 0)
8259 {
8260 Py_DECREF(u);
8261 return NULL;
8262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008263 maxchar_old = fixfct((PyUnicodeObject*)v);
8264 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8265 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008266 else {
Victor Stinner157f83f2011-09-28 21:41:31 +02008267 if (PyUnicode_CopyCharacters(v, 0,
8268 u, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008269 PyUnicode_GET_LENGTH(self)) < 0)
8270 {
8271 Py_DECREF(u);
8272 return NULL;
8273 }
8274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008275
8276 Py_DECREF(u);
8277 return v;
8278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008279}
8280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008282fixupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008284 /* No need to call PyUnicode_READY(self) because this function is only
8285 called as a callback from fixup() which does it already. */
8286 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8287 const int kind = PyUnicode_KIND(self);
8288 void *data = PyUnicode_DATA(self);
8289 int touched = 0;
8290 Py_UCS4 maxchar = 0;
8291 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008293 for (i = 0; i < len; ++i) {
8294 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8295 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8296 if (up != ch) {
8297 if (up > maxchar)
8298 maxchar = up;
8299 PyUnicode_WRITE(kind, data, i, up);
8300 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008302 else if (ch > maxchar)
8303 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008304 }
8305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008306 if (touched)
8307 return maxchar;
8308 else
8309 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008310}
8311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008312static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008313fixlower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008314{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008315 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8316 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8317 const int kind = PyUnicode_KIND(self);
8318 void *data = PyUnicode_DATA(self);
8319 int touched = 0;
8320 Py_UCS4 maxchar = 0;
8321 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008323 for(i = 0; i < len; ++i) {
8324 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8325 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8326 if (lo != ch) {
8327 if (lo > maxchar)
8328 maxchar = lo;
8329 PyUnicode_WRITE(kind, data, i, lo);
8330 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008332 else if (ch > maxchar)
8333 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 }
8335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008336 if (touched)
8337 return maxchar;
8338 else
8339 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340}
8341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008343fixswapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8346 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8347 const int kind = PyUnicode_KIND(self);
8348 void *data = PyUnicode_DATA(self);
8349 int touched = 0;
8350 Py_UCS4 maxchar = 0;
8351 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008353 for(i = 0; i < len; ++i) {
8354 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8355 Py_UCS4 nu = 0;
8356
8357 if (Py_UNICODE_ISUPPER(ch))
8358 nu = Py_UNICODE_TOLOWER(ch);
8359 else if (Py_UNICODE_ISLOWER(ch))
8360 nu = Py_UNICODE_TOUPPER(ch);
8361
8362 if (nu != 0) {
8363 if (nu > maxchar)
8364 maxchar = nu;
8365 PyUnicode_WRITE(kind, data, i, nu);
8366 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008368 else if (ch > maxchar)
8369 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008370 }
8371
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008372 if (touched)
8373 return maxchar;
8374 else
8375 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376}
8377
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008379fixcapitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008380{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8382 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8383 const int kind = PyUnicode_KIND(self);
8384 void *data = PyUnicode_DATA(self);
8385 int touched = 0;
8386 Py_UCS4 maxchar = 0;
8387 Py_ssize_t i = 0;
8388 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00008389
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008390 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392
8393 ch = PyUnicode_READ(kind, data, i);
8394 if (!Py_UNICODE_ISUPPER(ch)) {
8395 maxchar = Py_UNICODE_TOUPPER(ch);
8396 PyUnicode_WRITE(kind, data, i, maxchar);
8397 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008398 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008399 ++i;
8400 for(; i < len; ++i) {
8401 ch = PyUnicode_READ(kind, data, i);
8402 if (!Py_UNICODE_ISLOWER(ch)) {
8403 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8404 if (lo > maxchar)
8405 maxchar = lo;
8406 PyUnicode_WRITE(kind, data, i, lo);
8407 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008408 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008409 else if (ch > maxchar)
8410 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008412
8413 if (touched)
8414 return maxchar;
8415 else
8416 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008417}
8418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420fixtitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8423 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8424 const int kind = PyUnicode_KIND(self);
8425 void *data = PyUnicode_DATA(self);
8426 Py_UCS4 maxchar = 0;
8427 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008428 int previous_is_cased;
8429
8430 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008431 if (len == 1) {
8432 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8433 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
8434 if (ti != ch) {
8435 PyUnicode_WRITE(kind, data, i, ti);
8436 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 }
8438 else
8439 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008440 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008441 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 for(; i < len; ++i) {
8443 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8444 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00008445
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 nu = Py_UNICODE_TOTITLE(ch);
8450
8451 if (nu > maxchar)
8452 maxchar = nu;
8453 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00008454
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 if (Py_UNICODE_ISLOWER(ch) ||
8456 Py_UNICODE_ISUPPER(ch) ||
8457 Py_UNICODE_ISTITLE(ch))
8458 previous_is_cased = 1;
8459 else
8460 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463}
8464
Tim Peters8ce9f162004-08-27 01:49:32 +00008465PyObject *
8466PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008468 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008469 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00008471 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008472 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
8473 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00008474 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 Py_ssize_t sz, i, res_offset;
8476 Py_UCS4 maxchar = 0;
8477 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478
Tim Peters05eba1f2004-08-27 21:32:02 +00008479 fseq = PySequence_Fast(seq, "");
8480 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008481 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00008482 }
8483
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008484 /* NOTE: the following code can't call back into Python code,
8485 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00008486 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008487
Tim Peters05eba1f2004-08-27 21:32:02 +00008488 seqlen = PySequence_Fast_GET_SIZE(fseq);
8489 /* If empty sequence, return u"". */
8490 if (seqlen == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008491 res = PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00008493 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008494 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00008495 /* If singleton sequence with an exact Unicode, return that. */
8496 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 item = items[0];
8498 if (PyUnicode_CheckExact(item)) {
8499 Py_INCREF(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500 res = item;
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 goto Done;
8502 }
Tim Peters8ce9f162004-08-27 01:49:32 +00008503 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008504 else {
8505 /* Set up sep and seplen */
8506 if (separator == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507 /* fall back to a blank space separator */
8508 sep = PyUnicode_FromOrdinal(' ');
Victor Stinnere9a29352011-10-01 02:14:59 +02008509 if (!sep)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008510 goto onError;
Tim Peters05eba1f2004-08-27 21:32:02 +00008511 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008512 else {
8513 if (!PyUnicode_Check(separator)) {
8514 PyErr_Format(PyExc_TypeError,
8515 "separator: expected str instance,"
8516 " %.80s found",
8517 Py_TYPE(separator)->tp_name);
8518 goto onError;
8519 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 if (PyUnicode_READY(separator) == -1)
8521 goto onError;
8522 sep = separator;
8523 seplen = PyUnicode_GET_LENGTH(separator);
8524 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
8525 /* inc refcount to keep this code path symetric with the
8526 above case of a blank separator */
8527 Py_INCREF(sep);
Tim Peters05eba1f2004-08-27 21:32:02 +00008528 }
8529 }
8530
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008531 /* There are at least two things to join, or else we have a subclass
8532 * of str in the sequence.
8533 * Do a pre-pass to figure out the total amount of space we'll
8534 * need (sz), and see whether all argument are strings.
8535 */
8536 sz = 0;
8537 for (i = 0; i < seqlen; i++) {
8538 const Py_ssize_t old_sz = sz;
8539 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 if (!PyUnicode_Check(item)) {
8541 PyErr_Format(PyExc_TypeError,
8542 "sequence item %zd: expected str instance,"
8543 " %.80s found",
8544 i, Py_TYPE(item)->tp_name);
8545 goto onError;
8546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008547 if (PyUnicode_READY(item) == -1)
8548 goto onError;
8549 sz += PyUnicode_GET_LENGTH(item);
8550 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
8551 if (item_maxchar > maxchar)
8552 maxchar = item_maxchar;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008553 if (i != 0)
8554 sz += seplen;
8555 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
8556 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008558 goto onError;
8559 }
8560 }
Tim Petersced69f82003-09-16 20:30:58 +00008561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008563 if (res == NULL)
8564 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00008565
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008566 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008568 Py_ssize_t itemlen;
8569 item = items[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 itemlen = PyUnicode_GET_LENGTH(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 /* Copy item, and maybe the separator. */
8572 if (i) {
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008573 if (PyUnicode_CopyCharacters(res, res_offset,
8574 sep, 0, seplen) < 0)
8575 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576 res_offset += seplen;
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008578 if (PyUnicode_CopyCharacters(res, res_offset,
8579 item, 0, itemlen) < 0)
8580 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 res_offset += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00008582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00008584
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00008586 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 Py_XDECREF(sep);
8588 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00008591 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00008593 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594 return NULL;
8595}
8596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597#define FILL(kind, data, value, start, length) \
8598 do { \
8599 Py_ssize_t i_ = 0; \
8600 assert(kind != PyUnicode_WCHAR_KIND); \
8601 switch ((kind)) { \
8602 case PyUnicode_1BYTE_KIND: { \
8603 unsigned char * to_ = (unsigned char *)((data)) + (start); \
8604 memset(to_, (unsigned char)value, length); \
8605 break; \
8606 } \
8607 case PyUnicode_2BYTE_KIND: { \
8608 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
8609 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8610 break; \
8611 } \
8612 default: { \
8613 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
8614 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8615 break; \
8616 } \
8617 } \
8618 } while (0)
8619
Alexander Belopolsky40018472011-02-26 01:02:56 +00008620static PyUnicodeObject *
8621pad(PyUnicodeObject *self,
8622 Py_ssize_t left,
8623 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008625{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 PyObject *u;
8627 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008628 int kind;
8629 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630
8631 if (left < 0)
8632 left = 0;
8633 if (right < 0)
8634 right = 0;
8635
Tim Peters7a29bd52001-09-12 03:03:31 +00008636 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008637 Py_INCREF(self);
8638 return self;
8639 }
8640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
8642 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00008643 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
8644 return NULL;
8645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8647 if (fill > maxchar)
8648 maxchar = fill;
8649 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008650 if (!u)
8651 return NULL;
8652
8653 kind = PyUnicode_KIND(u);
8654 data = PyUnicode_DATA(u);
8655 if (left)
8656 FILL(kind, data, fill, 0, left);
8657 if (right)
8658 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinner157f83f2011-09-28 21:41:31 +02008659 if (PyUnicode_CopyCharacters(u, left,
8660 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008661 _PyUnicode_LENGTH(self)) < 0)
8662 {
8663 Py_DECREF(u);
8664 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008665 }
8666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 return (PyUnicodeObject*)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008668}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670
Alexander Belopolsky40018472011-02-26 01:02:56 +00008671PyObject *
8672PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675
8676 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680 switch(PyUnicode_KIND(string)) {
8681 case PyUnicode_1BYTE_KIND:
8682 list = ucs1lib_splitlines(
8683 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
8684 PyUnicode_GET_LENGTH(string), keepends);
8685 break;
8686 case PyUnicode_2BYTE_KIND:
8687 list = ucs2lib_splitlines(
8688 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
8689 PyUnicode_GET_LENGTH(string), keepends);
8690 break;
8691 case PyUnicode_4BYTE_KIND:
8692 list = ucs4lib_splitlines(
8693 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
8694 PyUnicode_GET_LENGTH(string), keepends);
8695 break;
8696 default:
8697 assert(0);
8698 list = 0;
8699 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700 Py_DECREF(string);
8701 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008702}
8703
Alexander Belopolsky40018472011-02-26 01:02:56 +00008704static PyObject *
8705split(PyUnicodeObject *self,
8706 PyUnicodeObject *substring,
8707 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008708{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 int kind1, kind2, kind;
8710 void *buf1, *buf2;
8711 Py_ssize_t len1, len2;
8712 PyObject* out;
8713
Guido van Rossumd57fd912000-03-10 22:53:23 +00008714 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008715 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 if (PyUnicode_READY(self) == -1)
8718 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 if (substring == NULL)
8721 switch(PyUnicode_KIND(self)) {
8722 case PyUnicode_1BYTE_KIND:
8723 return ucs1lib_split_whitespace(
8724 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8725 PyUnicode_GET_LENGTH(self), maxcount
8726 );
8727 case PyUnicode_2BYTE_KIND:
8728 return ucs2lib_split_whitespace(
8729 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
8730 PyUnicode_GET_LENGTH(self), maxcount
8731 );
8732 case PyUnicode_4BYTE_KIND:
8733 return ucs4lib_split_whitespace(
8734 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
8735 PyUnicode_GET_LENGTH(self), maxcount
8736 );
8737 default:
8738 assert(0);
8739 return NULL;
8740 }
8741
8742 if (PyUnicode_READY(substring) == -1)
8743 return NULL;
8744
8745 kind1 = PyUnicode_KIND(self);
8746 kind2 = PyUnicode_KIND(substring);
8747 kind = kind1 > kind2 ? kind1 : kind2;
8748 buf1 = PyUnicode_DATA(self);
8749 buf2 = PyUnicode_DATA(substring);
8750 if (kind1 != kind)
8751 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
8752 if (!buf1)
8753 return NULL;
8754 if (kind2 != kind)
8755 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
8756 if (!buf2) {
8757 if (kind1 != kind) PyMem_Free(buf1);
8758 return NULL;
8759 }
8760 len1 = PyUnicode_GET_LENGTH(self);
8761 len2 = PyUnicode_GET_LENGTH(substring);
8762
8763 switch(kind) {
8764 case PyUnicode_1BYTE_KIND:
8765 out = ucs1lib_split(
8766 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8767 break;
8768 case PyUnicode_2BYTE_KIND:
8769 out = ucs2lib_split(
8770 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8771 break;
8772 case PyUnicode_4BYTE_KIND:
8773 out = ucs4lib_split(
8774 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8775 break;
8776 default:
8777 out = NULL;
8778 }
8779 if (kind1 != kind)
8780 PyMem_Free(buf1);
8781 if (kind2 != kind)
8782 PyMem_Free(buf2);
8783 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784}
8785
Alexander Belopolsky40018472011-02-26 01:02:56 +00008786static PyObject *
8787rsplit(PyUnicodeObject *self,
8788 PyUnicodeObject *substring,
8789 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008791 int kind1, kind2, kind;
8792 void *buf1, *buf2;
8793 Py_ssize_t len1, len2;
8794 PyObject* out;
8795
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008796 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008797 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 if (PyUnicode_READY(self) == -1)
8800 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 if (substring == NULL)
8803 switch(PyUnicode_KIND(self)) {
8804 case PyUnicode_1BYTE_KIND:
8805 return ucs1lib_rsplit_whitespace(
8806 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8807 PyUnicode_GET_LENGTH(self), maxcount
8808 );
8809 case PyUnicode_2BYTE_KIND:
8810 return ucs2lib_rsplit_whitespace(
8811 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
8812 PyUnicode_GET_LENGTH(self), maxcount
8813 );
8814 case PyUnicode_4BYTE_KIND:
8815 return ucs4lib_rsplit_whitespace(
8816 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
8817 PyUnicode_GET_LENGTH(self), maxcount
8818 );
8819 default:
8820 assert(0);
8821 return NULL;
8822 }
8823
8824 if (PyUnicode_READY(substring) == -1)
8825 return NULL;
8826
8827 kind1 = PyUnicode_KIND(self);
8828 kind2 = PyUnicode_KIND(substring);
8829 kind = kind1 > kind2 ? kind1 : kind2;
8830 buf1 = PyUnicode_DATA(self);
8831 buf2 = PyUnicode_DATA(substring);
8832 if (kind1 != kind)
8833 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
8834 if (!buf1)
8835 return NULL;
8836 if (kind2 != kind)
8837 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
8838 if (!buf2) {
8839 if (kind1 != kind) PyMem_Free(buf1);
8840 return NULL;
8841 }
8842 len1 = PyUnicode_GET_LENGTH(self);
8843 len2 = PyUnicode_GET_LENGTH(substring);
8844
8845 switch(kind) {
8846 case PyUnicode_1BYTE_KIND:
8847 out = ucs1lib_rsplit(
8848 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8849 break;
8850 case PyUnicode_2BYTE_KIND:
8851 out = ucs2lib_rsplit(
8852 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8853 break;
8854 case PyUnicode_4BYTE_KIND:
8855 out = ucs4lib_rsplit(
8856 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8857 break;
8858 default:
8859 out = NULL;
8860 }
8861 if (kind1 != kind)
8862 PyMem_Free(buf1);
8863 if (kind2 != kind)
8864 PyMem_Free(buf2);
8865 return out;
8866}
8867
8868static Py_ssize_t
8869anylib_find(int kind, void *buf1, Py_ssize_t len1,
8870 void *buf2, Py_ssize_t len2, Py_ssize_t offset)
8871{
8872 switch(kind) {
8873 case PyUnicode_1BYTE_KIND:
8874 return ucs1lib_find(buf1, len1, buf2, len2, offset);
8875 case PyUnicode_2BYTE_KIND:
8876 return ucs2lib_find(buf1, len1, buf2, len2, offset);
8877 case PyUnicode_4BYTE_KIND:
8878 return ucs4lib_find(buf1, len1, buf2, len2, offset);
8879 }
8880 assert(0);
8881 return -1;
8882}
8883
8884static Py_ssize_t
8885anylib_count(int kind, void* sbuf, Py_ssize_t slen,
8886 void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
8887{
8888 switch(kind) {
8889 case PyUnicode_1BYTE_KIND:
8890 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
8891 case PyUnicode_2BYTE_KIND:
8892 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
8893 case PyUnicode_4BYTE_KIND:
8894 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
8895 }
8896 assert(0);
8897 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008898}
8899
Alexander Belopolsky40018472011-02-26 01:02:56 +00008900static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901replace(PyObject *self, PyObject *str1,
8902 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008904 PyObject *u;
8905 char *sbuf = PyUnicode_DATA(self);
8906 char *buf1 = PyUnicode_DATA(str1);
8907 char *buf2 = PyUnicode_DATA(str2);
8908 int srelease = 0, release1 = 0, release2 = 0;
8909 int skind = PyUnicode_KIND(self);
8910 int kind1 = PyUnicode_KIND(str1);
8911 int kind2 = PyUnicode_KIND(str2);
8912 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
8913 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
8914 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915
8916 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008919 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008921 if (skind < kind1)
8922 /* substring too wide to be present */
8923 goto nothing;
8924
8925 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00008926 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008927 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008929 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008930 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008931 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 Py_UCS4 u1, u2, maxchar;
8933 int mayshrink, rkind;
8934 u1 = PyUnicode_READ_CHAR(str1, 0);
8935 if (!findchar(sbuf, PyUnicode_KIND(self),
8936 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00008937 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008938 u2 = PyUnicode_READ_CHAR(str2, 0);
8939 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8940 /* Replacing u1 with u2 may cause a maxchar reduction in the
8941 result string. */
8942 mayshrink = maxchar > 127;
8943 if (u2 > maxchar) {
8944 maxchar = u2;
8945 mayshrink = 0;
8946 }
8947 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008948 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008949 goto error;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008950 if (PyUnicode_CopyCharacters(u, 0,
8951 (PyObject*)self, 0, slen) < 0)
8952 {
8953 Py_DECREF(u);
8954 return NULL;
8955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008956 rkind = PyUnicode_KIND(u);
8957 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
8958 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00008959 if (--maxcount < 0)
8960 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008961 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963 if (mayshrink) {
8964 PyObject *tmp = u;
8965 u = PyUnicode_FromKindAndData(rkind, PyUnicode_DATA(tmp),
8966 PyUnicode_GET_LENGTH(tmp));
8967 Py_DECREF(tmp);
8968 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008969 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008970 int rkind = skind;
8971 char *res;
8972 if (kind1 < rkind) {
8973 /* widen substring */
8974 buf1 = _PyUnicode_AsKind(str1, rkind);
8975 if (!buf1) goto error;
8976 release1 = 1;
8977 }
8978 i = anylib_find(rkind, sbuf, slen, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008979 if (i < 0)
8980 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 if (rkind > kind2) {
8982 /* widen replacement */
8983 buf2 = _PyUnicode_AsKind(str2, rkind);
8984 if (!buf2) goto error;
8985 release2 = 1;
8986 }
8987 else if (rkind < kind2) {
8988 /* widen self and buf1 */
8989 rkind = kind2;
8990 if (release1) PyMem_Free(buf1);
8991 sbuf = _PyUnicode_AsKind(self, rkind);
8992 if (!sbuf) goto error;
8993 srelease = 1;
8994 buf1 = _PyUnicode_AsKind(str1, rkind);
8995 if (!buf1) goto error;
8996 release1 = 1;
8997 }
8998 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, slen));
8999 if (!res) {
9000 PyErr_NoMemory();
9001 goto error;
9002 }
9003 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009004 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9006 buf2,
9007 PyUnicode_KIND_SIZE(rkind, len2));
9008 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009009
9010 while ( --maxcount > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 i = anylib_find(rkind, sbuf+PyUnicode_KIND_SIZE(rkind, i),
9012 slen-i,
9013 buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009014 if (i == -1)
9015 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9017 buf2,
9018 PyUnicode_KIND_SIZE(rkind, len2));
9019 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009020 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021
9022 u = PyUnicode_FromKindAndData(rkind, res, slen);
9023 PyMem_Free(res);
9024 if (!u) goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009026 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009028 Py_ssize_t n, i, j, ires;
9029 Py_ssize_t product, new_size;
9030 int rkind = skind;
9031 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033 if (kind1 < rkind) {
9034 buf1 = _PyUnicode_AsKind(str1, rkind);
9035 if (!buf1) goto error;
9036 release1 = 1;
9037 }
9038 n = anylib_count(rkind, sbuf, slen, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009039 if (n == 0)
9040 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041 if (kind2 < rkind) {
9042 buf2 = _PyUnicode_AsKind(str2, rkind);
9043 if (!buf2) goto error;
9044 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009046 else if (kind2 > rkind) {
9047 rkind = kind2;
9048 sbuf = _PyUnicode_AsKind(self, rkind);
9049 if (!sbuf) goto error;
9050 srelease = 1;
9051 if (release1) PyMem_Free(buf1);
9052 buf1 = _PyUnicode_AsKind(str1, rkind);
9053 if (!buf1) goto error;
9054 release1 = 1;
9055 }
9056 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9057 PyUnicode_GET_LENGTH(str1))); */
9058 product = n * (len2-len1);
9059 if ((product / (len2-len1)) != n) {
9060 PyErr_SetString(PyExc_OverflowError,
9061 "replace string is too long");
9062 goto error;
9063 }
9064 new_size = slen + product;
9065 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9066 PyErr_SetString(PyExc_OverflowError,
9067 "replace string is too long");
9068 goto error;
9069 }
9070 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, new_size));
9071 if (!res)
9072 goto error;
9073 ires = i = 0;
9074 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009075 while (n-- > 0) {
9076 /* look for next match */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 j = anylib_find(rkind,
9078 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9079 slen-i, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009080 if (j == -1)
9081 break;
9082 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009083 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9085 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9086 PyUnicode_KIND_SIZE(rkind, j-i));
9087 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009088 }
9089 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090 if (len2 > 0) {
9091 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9092 buf2,
9093 PyUnicode_KIND_SIZE(rkind, len2));
9094 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009095 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009096 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009099 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9101 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9102 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009103 } else {
9104 /* interleave */
9105 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9107 buf2,
9108 PyUnicode_KIND_SIZE(rkind, len2));
9109 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009110 if (--n <= 0)
9111 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9113 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9114 PyUnicode_KIND_SIZE(rkind, 1));
9115 ires++;
9116 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009117 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9119 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9120 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122 u = PyUnicode_FromKindAndData(rkind, res, new_size);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02009123 PyMem_Free(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009124 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 if (srelease)
9126 PyMem_FREE(sbuf);
9127 if (release1)
9128 PyMem_FREE(buf1);
9129 if (release2)
9130 PyMem_FREE(buf2);
9131 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009132
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009134 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135 if (srelease)
9136 PyMem_FREE(sbuf);
9137 if (release1)
9138 PyMem_FREE(buf1);
9139 if (release2)
9140 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009141 if (PyUnicode_CheckExact(self)) {
9142 Py_INCREF(self);
9143 return (PyObject *) self;
9144 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009145 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 error:
9147 if (srelease && sbuf)
9148 PyMem_FREE(sbuf);
9149 if (release1 && buf1)
9150 PyMem_FREE(buf1);
9151 if (release2 && buf2)
9152 PyMem_FREE(buf2);
9153 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154}
9155
9156/* --- Unicode Object Methods --------------------------------------------- */
9157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009158PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009159 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160\n\
9161Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009162characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163
9164static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009165unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009167 return fixup(self, fixtitle);
9168}
9169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009170PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009171 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009172\n\
9173Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009174have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009175
9176static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009177unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179 return fixup(self, fixcapitalize);
9180}
9181
9182#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009183PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009184 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185\n\
9186Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009187normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188
9189static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009190unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191{
9192 PyObject *list;
9193 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009194 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195
Guido van Rossumd57fd912000-03-10 22:53:23 +00009196 /* Split into words */
9197 list = split(self, NULL, -1);
9198 if (!list)
9199 return NULL;
9200
9201 /* Capitalize each word */
9202 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9203 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009204 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009205 if (item == NULL)
9206 goto onError;
9207 Py_DECREF(PyList_GET_ITEM(list, i));
9208 PyList_SET_ITEM(list, i, item);
9209 }
9210
9211 /* Join the words to form a new string */
9212 item = PyUnicode_Join(NULL, list);
9213
Benjamin Peterson29060642009-01-31 22:14:21 +00009214 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009215 Py_DECREF(list);
9216 return (PyObject *)item;
9217}
9218#endif
9219
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009220/* Argument converter. Coerces to a single unicode character */
9221
9222static int
9223convert_uc(PyObject *obj, void *addr)
9224{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009226 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009227
Benjamin Peterson14339b62009-01-31 16:36:08 +00009228 uniobj = PyUnicode_FromObject(obj);
9229 if (uniobj == NULL) {
9230 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009231 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009232 return 0;
9233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009235 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009236 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009237 Py_DECREF(uniobj);
9238 return 0;
9239 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009240 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009241 Py_DECREF(uniobj);
9242 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009243}
9244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009245PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009246 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009248Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009249done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250
9251static PyObject *
9252unicode_center(PyUnicodeObject *self, PyObject *args)
9253{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009254 Py_ssize_t marg, left;
9255 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 Py_UCS4 fillchar = ' ';
9257
Victor Stinnere9a29352011-10-01 02:14:59 +02009258 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260
Victor Stinnere9a29352011-10-01 02:14:59 +02009261 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262 return NULL;
9263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 Py_INCREF(self);
9266 return (PyObject*) self;
9267 }
9268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009270 left = marg / 2 + (marg & width & 1);
9271
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009272 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273}
9274
Marc-André Lemburge5034372000-08-08 08:04:29 +00009275#if 0
9276
9277/* This code should go into some future Unicode collation support
9278 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009279 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009280
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009281/* speedy UTF-16 code point order comparison */
9282/* gleaned from: */
9283/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9284
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009285static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009286{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009287 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009288 0, 0, 0, 0, 0, 0, 0, 0,
9289 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009290 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009291};
9292
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293static int
9294unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9295{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009296 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009297
Guido van Rossumd57fd912000-03-10 22:53:23 +00009298 Py_UNICODE *s1 = str1->str;
9299 Py_UNICODE *s2 = str2->str;
9300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 len1 = str1->_base._base.length;
9302 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +00009303
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00009305 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009306
9307 c1 = *s1++;
9308 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00009309
Benjamin Peterson29060642009-01-31 22:14:21 +00009310 if (c1 > (1<<11) * 26)
9311 c1 += utf16Fixup[c1>>11];
9312 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009313 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009314 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00009315
9316 if (c1 != c2)
9317 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00009318
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009319 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320 }
9321
9322 return (len1 < len2) ? -1 : (len1 != len2);
9323}
9324
Marc-André Lemburge5034372000-08-08 08:04:29 +00009325#else
9326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327/* This function assumes that str1 and str2 are readied by the caller. */
9328
Marc-André Lemburge5034372000-08-08 08:04:29 +00009329static int
9330unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 int kind1, kind2;
9333 void *data1, *data2;
9334 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 kind1 = PyUnicode_KIND(str1);
9337 kind2 = PyUnicode_KIND(str2);
9338 data1 = PyUnicode_DATA(str1);
9339 data2 = PyUnicode_DATA(str2);
9340 len1 = PyUnicode_GET_LENGTH(str1);
9341 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +00009342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343 for (i = 0; i < len1 && i < len2; ++i) {
9344 Py_UCS4 c1, c2;
9345 c1 = PyUnicode_READ(kind1, data1, i);
9346 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +00009347
9348 if (c1 != c2)
9349 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009350 }
9351
9352 return (len1 < len2) ? -1 : (len1 != len2);
9353}
9354
9355#endif
9356
Alexander Belopolsky40018472011-02-26 01:02:56 +00009357int
9358PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9361 if (PyUnicode_READY(left) == -1 ||
9362 PyUnicode_READY(right) == -1)
9363 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009364 return unicode_compare((PyUnicodeObject *)left,
9365 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009367 PyErr_Format(PyExc_TypeError,
9368 "Can't compare %.100s and %.100s",
9369 left->ob_type->tp_name,
9370 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371 return -1;
9372}
9373
Martin v. Löwis5b222132007-06-10 09:51:05 +00009374int
9375PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
9376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 Py_ssize_t i;
9378 int kind;
9379 void *data;
9380 Py_UCS4 chr;
9381
Martin v. Löwis5b222132007-06-10 09:51:05 +00009382 assert(PyUnicode_Check(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009383 if (PyUnicode_READY(uni) == -1)
9384 return -1;
9385 kind = PyUnicode_KIND(uni);
9386 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +00009387 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
9389 if (chr != str[i])
9390 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00009391 /* This check keeps Python strings that end in '\0' from comparing equal
9392 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +00009394 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009395 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00009396 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009397 return 0;
9398}
9399
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009400
Benjamin Peterson29060642009-01-31 22:14:21 +00009401#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00009402 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009403
Alexander Belopolsky40018472011-02-26 01:02:56 +00009404PyObject *
9405PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009406{
9407 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009408
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009409 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9410 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 if (PyUnicode_READY(left) == -1 ||
9412 PyUnicode_READY(right) == -1)
9413 return NULL;
9414 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
9415 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009416 if (op == Py_EQ) {
9417 Py_INCREF(Py_False);
9418 return Py_False;
9419 }
9420 if (op == Py_NE) {
9421 Py_INCREF(Py_True);
9422 return Py_True;
9423 }
9424 }
9425 if (left == right)
9426 result = 0;
9427 else
9428 result = unicode_compare((PyUnicodeObject *)left,
9429 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009430
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009431 /* Convert the return value to a Boolean */
9432 switch (op) {
9433 case Py_EQ:
9434 v = TEST_COND(result == 0);
9435 break;
9436 case Py_NE:
9437 v = TEST_COND(result != 0);
9438 break;
9439 case Py_LE:
9440 v = TEST_COND(result <= 0);
9441 break;
9442 case Py_GE:
9443 v = TEST_COND(result >= 0);
9444 break;
9445 case Py_LT:
9446 v = TEST_COND(result == -1);
9447 break;
9448 case Py_GT:
9449 v = TEST_COND(result == 1);
9450 break;
9451 default:
9452 PyErr_BadArgument();
9453 return NULL;
9454 }
9455 Py_INCREF(v);
9456 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009457 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009458
Brian Curtindfc80e32011-08-10 20:28:54 -05009459 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009460}
9461
Alexander Belopolsky40018472011-02-26 01:02:56 +00009462int
9463PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00009464{
Thomas Wouters477c8d52006-05-27 19:21:47 +00009465 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 int kind1, kind2, kind;
9467 void *buf1, *buf2;
9468 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009469 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009470
9471 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00009472 sub = PyUnicode_FromObject(element);
9473 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 PyErr_Format(PyExc_TypeError,
9475 "'in <string>' requires string as left operand, not %s",
9476 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009477 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 if (PyUnicode_READY(sub) == -1)
9480 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009481
Thomas Wouters477c8d52006-05-27 19:21:47 +00009482 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +02009483 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009484 Py_DECREF(sub);
9485 return -1;
9486 }
9487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 kind1 = PyUnicode_KIND(str);
9489 kind2 = PyUnicode_KIND(sub);
9490 kind = kind1 > kind2 ? kind1 : kind2;
9491 buf1 = PyUnicode_DATA(str);
9492 buf2 = PyUnicode_DATA(sub);
9493 if (kind1 != kind)
9494 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
9495 if (!buf1) {
9496 Py_DECREF(sub);
9497 return -1;
9498 }
9499 if (kind2 != kind)
9500 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
9501 if (!buf2) {
9502 Py_DECREF(sub);
9503 if (kind1 != kind) PyMem_Free(buf1);
9504 return -1;
9505 }
9506 len1 = PyUnicode_GET_LENGTH(str);
9507 len2 = PyUnicode_GET_LENGTH(sub);
9508
9509 switch(kind) {
9510 case PyUnicode_1BYTE_KIND:
9511 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
9512 break;
9513 case PyUnicode_2BYTE_KIND:
9514 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
9515 break;
9516 case PyUnicode_4BYTE_KIND:
9517 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
9518 break;
9519 default:
9520 result = -1;
9521 assert(0);
9522 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009523
9524 Py_DECREF(str);
9525 Py_DECREF(sub);
9526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 if (kind1 != kind)
9528 PyMem_Free(buf1);
9529 if (kind2 != kind)
9530 PyMem_Free(buf2);
9531
Guido van Rossum403d68b2000-03-13 15:55:09 +00009532 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009533}
9534
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535/* Concat to string or Unicode object giving a new Unicode object. */
9536
Alexander Belopolsky40018472011-02-26 01:02:56 +00009537PyObject *
9538PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009539{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540 PyObject *u = NULL, *v = NULL, *w;
9541 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542
9543 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009546 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009548 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550
9551 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +02009552 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555 }
Victor Stinnera464fc12011-10-02 20:39:30 +02009556 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009559 }
9560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +02009562 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 w = PyUnicode_New(
9566 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
9567 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009568 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 goto onError;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009570 if (PyUnicode_CopyCharacters(w, 0, u, 0, PyUnicode_GET_LENGTH(u)) < 0)
9571 goto onError;
Victor Stinner157f83f2011-09-28 21:41:31 +02009572 if (PyUnicode_CopyCharacters(w, PyUnicode_GET_LENGTH(u),
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009573 v, 0,
9574 PyUnicode_GET_LENGTH(v)) < 0)
9575 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576 Py_DECREF(u);
9577 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579
Benjamin Peterson29060642009-01-31 22:14:21 +00009580 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581 Py_XDECREF(u);
9582 Py_XDECREF(v);
9583 return NULL;
9584}
9585
Walter Dörwald1ab83302007-05-18 17:15:44 +00009586void
9587PyUnicode_Append(PyObject **pleft, PyObject *right)
9588{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009589 PyObject *new;
9590 if (*pleft == NULL)
9591 return;
9592 if (right == NULL || !PyUnicode_Check(*pleft)) {
9593 Py_DECREF(*pleft);
9594 *pleft = NULL;
9595 return;
9596 }
9597 new = PyUnicode_Concat(*pleft, right);
9598 Py_DECREF(*pleft);
9599 *pleft = new;
Walter Dörwald1ab83302007-05-18 17:15:44 +00009600}
9601
9602void
9603PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
9604{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009605 PyUnicode_Append(pleft, right);
9606 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00009607}
9608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009609PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009610 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00009612Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009613string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009614interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009615
9616static PyObject *
9617unicode_count(PyUnicodeObject *self, PyObject *args)
9618{
9619 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009620 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009621 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009622 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009623 int kind1, kind2, kind;
9624 void *buf1, *buf2;
9625 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626
Jesus Ceaac451502011-04-20 17:09:23 +02009627 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
9628 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009629 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00009630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631 kind1 = PyUnicode_KIND(self);
9632 kind2 = PyUnicode_KIND(substring);
9633 kind = kind1 > kind2 ? kind1 : kind2;
9634 buf1 = PyUnicode_DATA(self);
9635 buf2 = PyUnicode_DATA(substring);
9636 if (kind1 != kind)
9637 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9638 if (!buf1) {
9639 Py_DECREF(substring);
9640 return NULL;
9641 }
9642 if (kind2 != kind)
9643 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9644 if (!buf2) {
9645 Py_DECREF(substring);
9646 if (kind1 != kind) PyMem_Free(buf1);
9647 return NULL;
9648 }
9649 len1 = PyUnicode_GET_LENGTH(self);
9650 len2 = PyUnicode_GET_LENGTH(substring);
9651
9652 ADJUST_INDICES(start, end, len1);
9653 switch(kind) {
9654 case PyUnicode_1BYTE_KIND:
9655 iresult = ucs1lib_count(
9656 ((Py_UCS1*)buf1) + start, end - start,
9657 buf2, len2, PY_SSIZE_T_MAX
9658 );
9659 break;
9660 case PyUnicode_2BYTE_KIND:
9661 iresult = ucs2lib_count(
9662 ((Py_UCS2*)buf1) + start, end - start,
9663 buf2, len2, PY_SSIZE_T_MAX
9664 );
9665 break;
9666 case PyUnicode_4BYTE_KIND:
9667 iresult = ucs4lib_count(
9668 ((Py_UCS4*)buf1) + start, end - start,
9669 buf2, len2, PY_SSIZE_T_MAX
9670 );
9671 break;
9672 default:
9673 assert(0); iresult = 0;
9674 }
9675
9676 result = PyLong_FromSsize_t(iresult);
9677
9678 if (kind1 != kind)
9679 PyMem_Free(buf1);
9680 if (kind2 != kind)
9681 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682
9683 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009684
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685 return result;
9686}
9687
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009688PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00009689 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00009691Encode S using the codec registered for encoding. Default encoding\n\
9692is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00009693handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009694a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
9695'xmlcharrefreplace' as well as any other name registered with\n\
9696codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009697
9698static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00009699unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009700{
Benjamin Peterson308d6372009-09-18 21:42:35 +00009701 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00009702 char *encoding = NULL;
9703 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00009704
Benjamin Peterson308d6372009-09-18 21:42:35 +00009705 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
9706 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00009708 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00009709}
9710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009711PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009712 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009713\n\
9714Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009715If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009716
9717static PyObject*
9718unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
9719{
9720 Py_UNICODE *e;
9721 Py_UNICODE *p;
9722 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009723 Py_UNICODE *qe;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 Py_ssize_t i, j, incr, wstr_length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009725 PyUnicodeObject *u;
9726 int tabsize = 8;
9727
9728 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00009729 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731 if (PyUnicode_AsUnicodeAndSize((PyObject *)self, &wstr_length) == NULL)
9732 return NULL;
9733
Thomas Wouters7e474022000-07-16 12:04:32 +00009734 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009735 i = 0; /* chars up to and including most recent \n or \r */
9736 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009737 e = _PyUnicode_WSTR(self) + wstr_length; /* end of input */
9738 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009739 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009740 if (tabsize > 0) {
9741 incr = tabsize - (j % tabsize); /* cannot overflow */
9742 if (j > PY_SSIZE_T_MAX - incr)
9743 goto overflow1;
9744 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009745 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009746 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009747 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00009748 if (j > PY_SSIZE_T_MAX - 1)
9749 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750 j++;
9751 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009752 if (i > PY_SSIZE_T_MAX - j)
9753 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009754 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009755 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009756 }
9757 }
9758
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009759 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00009761
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762 /* Second pass: create output string and fill it */
9763 u = _PyUnicode_New(i + j);
9764 if (!u)
9765 return NULL;
9766
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009767 j = 0; /* same as in first pass */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 q = _PyUnicode_WSTR(u); /* next output char */
9769 qe = _PyUnicode_WSTR(u) + PyUnicode_GET_SIZE(u); /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009771 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009773 if (tabsize > 0) {
9774 i = tabsize - (j % tabsize);
9775 j += i;
9776 while (i--) {
9777 if (q >= qe)
9778 goto overflow2;
9779 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009780 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009781 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009782 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009783 else {
9784 if (q >= qe)
9785 goto overflow2;
9786 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009787 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788 if (*p == '\n' || *p == '\r')
9789 j = 0;
9790 }
9791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 if (PyUnicode_READY(u) == -1) {
9793 Py_DECREF(u);
9794 return NULL;
9795 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009797
9798 overflow2:
9799 Py_DECREF(u);
9800 overflow1:
9801 PyErr_SetString(PyExc_OverflowError, "new string is too long");
9802 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803}
9804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009805PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009806 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807\n\
9808Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +08009809such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810arguments start and end are interpreted as in slice notation.\n\
9811\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009812Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813
9814static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009816{
Jesus Ceaac451502011-04-20 17:09:23 +02009817 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00009818 Py_ssize_t start;
9819 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009820 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009821
Jesus Ceaac451502011-04-20 17:09:23 +02009822 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
9823 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 if (PyUnicode_READY(self) == -1)
9827 return NULL;
9828 if (PyUnicode_READY(substring) == -1)
9829 return NULL;
9830
9831 result = any_find_slice(
9832 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
9833 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00009834 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835
9836 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 if (result == -2)
9839 return NULL;
9840
Christian Heimes217cfd12007-12-02 14:31:20 +00009841 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009842}
9843
9844static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +02009845unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02009847 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
9848 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851}
9852
Guido van Rossumc2504932007-09-18 19:42:40 +00009853/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +01009854 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +00009855static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +00009856unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857{
Guido van Rossumc2504932007-09-18 19:42:40 +00009858 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +01009859 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +00009860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009861 if (_PyUnicode_HASH(self) != -1)
9862 return _PyUnicode_HASH(self);
9863 if (PyUnicode_READY(self) == -1)
9864 return -1;
9865 len = PyUnicode_GET_LENGTH(self);
9866
9867 /* The hash function as a macro, gets expanded three times below. */
9868#define HASH(P) \
9869 x = (Py_uhash_t)*P << 7; \
9870 while (--len >= 0) \
9871 x = (1000003*x) ^ (Py_uhash_t)*P++;
9872
9873 switch (PyUnicode_KIND(self)) {
9874 case PyUnicode_1BYTE_KIND: {
9875 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
9876 HASH(c);
9877 break;
9878 }
9879 case PyUnicode_2BYTE_KIND: {
9880 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
9881 HASH(s);
9882 break;
9883 }
9884 default: {
9885 Py_UCS4 *l;
9886 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
9887 "Impossible switch case in unicode_hash");
9888 l = PyUnicode_4BYTE_DATA(self);
9889 HASH(l);
9890 break;
9891 }
9892 }
9893 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
9894
Guido van Rossumc2504932007-09-18 19:42:40 +00009895 if (x == -1)
9896 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +00009898 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009900#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +00009901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009902PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009903 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009905Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009906
9907static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009910 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +02009911 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +00009912 Py_ssize_t start;
9913 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009914
Jesus Ceaac451502011-04-20 17:09:23 +02009915 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
9916 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009918
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 if (PyUnicode_READY(self) == -1)
9920 return NULL;
9921 if (PyUnicode_READY(substring) == -1)
9922 return NULL;
9923
9924 result = any_find_slice(
9925 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
9926 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00009927 );
Guido van Rossumd57fd912000-03-10 22:53:23 +00009928
9929 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009930
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 if (result == -2)
9932 return NULL;
9933
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934 if (result < 0) {
9935 PyErr_SetString(PyExc_ValueError, "substring not found");
9936 return NULL;
9937 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009938
Christian Heimes217cfd12007-12-02 14:31:20 +00009939 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009940}
9941
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009942PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009943 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009944\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00009945Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009946at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947
9948static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009949unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009950{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 Py_ssize_t i, length;
9952 int kind;
9953 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009954 int cased;
9955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 if (PyUnicode_READY(self) == -1)
9957 return NULL;
9958 length = PyUnicode_GET_LENGTH(self);
9959 kind = PyUnicode_KIND(self);
9960 data = PyUnicode_DATA(self);
9961
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 if (length == 1)
9964 return PyBool_FromLong(
9965 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009967 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009969 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00009970
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 for (i = 0; i < length; i++) {
9973 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009974
Benjamin Peterson29060642009-01-31 22:14:21 +00009975 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
9976 return PyBool_FromLong(0);
9977 else if (!cased && Py_UNICODE_ISLOWER(ch))
9978 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009979 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00009980 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981}
9982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009983PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009984 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00009986Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009987at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009988
9989static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009990unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009992 Py_ssize_t i, length;
9993 int kind;
9994 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995 int cased;
9996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 if (PyUnicode_READY(self) == -1)
9998 return NULL;
9999 length = PyUnicode_GET_LENGTH(self);
10000 kind = PyUnicode_KIND(self);
10001 data = PyUnicode_DATA(self);
10002
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 if (length == 1)
10005 return PyBool_FromLong(
10006 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010007
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010008 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010010 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010011
Guido van Rossumd57fd912000-03-10 22:53:23 +000010012 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 for (i = 0; i < length; i++) {
10014 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010015
Benjamin Peterson29060642009-01-31 22:14:21 +000010016 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10017 return PyBool_FromLong(0);
10018 else if (!cased && Py_UNICODE_ISUPPER(ch))
10019 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010020 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010021 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022}
10023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010024PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010025 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010026\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010027Return True if S is a titlecased string and there is at least one\n\
10028character in S, i.e. upper- and titlecase characters may only\n\
10029follow uncased characters and lowercase characters only cased ones.\n\
10030Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031
10032static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010033unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 Py_ssize_t i, length;
10036 int kind;
10037 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010038 int cased, previous_is_cased;
10039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 if (PyUnicode_READY(self) == -1)
10041 return NULL;
10042 length = PyUnicode_GET_LENGTH(self);
10043 kind = PyUnicode_KIND(self);
10044 data = PyUnicode_DATA(self);
10045
Guido van Rossumd57fd912000-03-10 22:53:23 +000010046 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 if (length == 1) {
10048 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10049 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10050 (Py_UNICODE_ISUPPER(ch) != 0));
10051 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010052
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010053 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010055 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010056
Guido van Rossumd57fd912000-03-10 22:53:23 +000010057 cased = 0;
10058 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 for (i = 0; i < length; i++) {
10060 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010061
Benjamin Peterson29060642009-01-31 22:14:21 +000010062 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10063 if (previous_is_cased)
10064 return PyBool_FromLong(0);
10065 previous_is_cased = 1;
10066 cased = 1;
10067 }
10068 else if (Py_UNICODE_ISLOWER(ch)) {
10069 if (!previous_is_cased)
10070 return PyBool_FromLong(0);
10071 previous_is_cased = 1;
10072 cased = 1;
10073 }
10074 else
10075 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010076 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010077 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010078}
10079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010080PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010081 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010083Return True if all characters in S are whitespace\n\
10084and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010085
10086static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010087unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010088{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 Py_ssize_t i, length;
10090 int kind;
10091 void *data;
10092
10093 if (PyUnicode_READY(self) == -1)
10094 return NULL;
10095 length = PyUnicode_GET_LENGTH(self);
10096 kind = PyUnicode_KIND(self);
10097 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 if (length == 1)
10101 return PyBool_FromLong(
10102 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010104 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010106 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 for (i = 0; i < length; i++) {
10109 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010110 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010111 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010112 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010113 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114}
10115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010116PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010117 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010118\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010119Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010120and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010121
10122static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010123unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010124{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 Py_ssize_t i, length;
10126 int kind;
10127 void *data;
10128
10129 if (PyUnicode_READY(self) == -1)
10130 return NULL;
10131 length = PyUnicode_GET_LENGTH(self);
10132 kind = PyUnicode_KIND(self);
10133 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010134
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010135 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 if (length == 1)
10137 return PyBool_FromLong(
10138 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010139
10140 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010142 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 for (i = 0; i < length; i++) {
10145 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010146 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010147 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010148 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010149}
10150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010151PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010152 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010153\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010154Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010155and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010156
10157static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010158unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 int kind;
10161 void *data;
10162 Py_ssize_t len, i;
10163
10164 if (PyUnicode_READY(self) == -1)
10165 return NULL;
10166
10167 kind = PyUnicode_KIND(self);
10168 data = PyUnicode_DATA(self);
10169 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010170
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010171 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 if (len == 1) {
10173 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10174 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10175 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010176
10177 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010179 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 for (i = 0; i < len; i++) {
10182 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010183 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010184 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010185 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010186 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010187}
10188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010189PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010190 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010191\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010192Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010193False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010194
10195static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010196unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010197{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 Py_ssize_t i, length;
10199 int kind;
10200 void *data;
10201
10202 if (PyUnicode_READY(self) == -1)
10203 return NULL;
10204 length = PyUnicode_GET_LENGTH(self);
10205 kind = PyUnicode_KIND(self);
10206 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010207
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 if (length == 1)
10210 return PyBool_FromLong(
10211 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010213 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010215 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 for (i = 0; i < length; i++) {
10218 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010219 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010220 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010221 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010222}
10223
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010224PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010225 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010227Return True if all characters in S are digits\n\
10228and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010229
10230static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010231unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010232{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 Py_ssize_t i, length;
10234 int kind;
10235 void *data;
10236
10237 if (PyUnicode_READY(self) == -1)
10238 return NULL;
10239 length = PyUnicode_GET_LENGTH(self);
10240 kind = PyUnicode_KIND(self);
10241 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010242
Guido van Rossumd57fd912000-03-10 22:53:23 +000010243 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 if (length == 1) {
10245 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10246 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
10247 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010249 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010251 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 for (i = 0; i < length; i++) {
10254 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010255 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010257 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010258}
10259
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010260PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010261 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010262\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010263Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010264False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010265
10266static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010267unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 Py_ssize_t i, length;
10270 int kind;
10271 void *data;
10272
10273 if (PyUnicode_READY(self) == -1)
10274 return NULL;
10275 length = PyUnicode_GET_LENGTH(self);
10276 kind = PyUnicode_KIND(self);
10277 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 if (length == 1)
10281 return PyBool_FromLong(
10282 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010284 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010286 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 for (i = 0; i < length; i++) {
10289 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010290 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010291 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010292 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293}
10294
Martin v. Löwis47383402007-08-15 07:32:56 +000010295int
10296PyUnicode_IsIdentifier(PyObject *self)
10297{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 int kind;
10299 void *data;
10300 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010301 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000010302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 if (PyUnicode_READY(self) == -1) {
10304 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000010305 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 }
10307
10308 /* Special case for empty strings */
10309 if (PyUnicode_GET_LENGTH(self) == 0)
10310 return 0;
10311 kind = PyUnicode_KIND(self);
10312 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000010313
10314 /* PEP 3131 says that the first character must be in
10315 XID_Start and subsequent characters in XID_Continue,
10316 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000010317 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000010318 letters, digits, underscore). However, given the current
10319 definition of XID_Start and XID_Continue, it is sufficient
10320 to check just for these, except that _ must be allowed
10321 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050010323 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000010324 return 0;
10325
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040010326 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010328 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000010329 return 1;
10330}
10331
10332PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010333 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000010334\n\
10335Return True if S is a valid identifier according\n\
10336to the language definition.");
10337
10338static PyObject*
10339unicode_isidentifier(PyObject *self)
10340{
10341 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
10342}
10343
Georg Brandl559e5d72008-06-11 18:37:52 +000010344PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010345 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000010346\n\
10347Return True if all characters in S are considered\n\
10348printable in repr() or S is empty, False otherwise.");
10349
10350static PyObject*
10351unicode_isprintable(PyObject *self)
10352{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 Py_ssize_t i, length;
10354 int kind;
10355 void *data;
10356
10357 if (PyUnicode_READY(self) == -1)
10358 return NULL;
10359 length = PyUnicode_GET_LENGTH(self);
10360 kind = PyUnicode_KIND(self);
10361 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000010362
10363 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 if (length == 1)
10365 return PyBool_FromLong(
10366 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000010367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 for (i = 0; i < length; i++) {
10369 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010370 Py_RETURN_FALSE;
10371 }
10372 }
10373 Py_RETURN_TRUE;
10374}
10375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010376PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000010377 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010378\n\
10379Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000010380iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010381
10382static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010383unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010384{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010385 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386}
10387
Martin v. Löwis18e16552006-02-15 17:27:45 +000010388static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389unicode_length(PyUnicodeObject *self)
10390{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 if (PyUnicode_READY(self) == -1)
10392 return -1;
10393 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394}
10395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010396PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010397 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010399Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010400done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401
10402static PyObject *
10403unicode_ljust(PyUnicodeObject *self, PyObject *args)
10404{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010405 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 Py_UCS4 fillchar = ' ';
10407
10408 if (PyUnicode_READY(self) == -1)
10409 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010410
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010411 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 return NULL;
10413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415 Py_INCREF(self);
10416 return (PyObject*) self;
10417 }
10418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420}
10421
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010422PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010423 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010424\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010425Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426
10427static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010428unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430 return fixup(self, fixlower);
10431}
10432
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010433#define LEFTSTRIP 0
10434#define RIGHTSTRIP 1
10435#define BOTHSTRIP 2
10436
10437/* Arrays indexed by above */
10438static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
10439
10440#define STRIPNAME(i) (stripformat[i]+3)
10441
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010442/* externally visible for str.strip(unicode) */
10443PyObject *
10444_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
10445{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 void *data;
10447 int kind;
10448 Py_ssize_t i, j, len;
10449 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
10452 return NULL;
10453
10454 kind = PyUnicode_KIND(self);
10455 data = PyUnicode_DATA(self);
10456 len = PyUnicode_GET_LENGTH(self);
10457 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
10458 PyUnicode_DATA(sepobj),
10459 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010460
Benjamin Peterson14339b62009-01-31 16:36:08 +000010461 i = 0;
10462 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 while (i < len &&
10464 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010465 i++;
10466 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010467 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010468
Benjamin Peterson14339b62009-01-31 16:36:08 +000010469 j = len;
10470 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010471 do {
10472 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 } while (j >= i &&
10474 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000010475 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010476 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010477
Victor Stinner12bab6d2011-10-01 01:53:49 +020010478 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479}
10480
10481PyObject*
10482PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
10483{
10484 unsigned char *data;
10485 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020010486 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487
Victor Stinnerde636f32011-10-01 03:55:54 +020010488 if (PyUnicode_READY(self) == -1)
10489 return NULL;
10490
10491 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
10492
Victor Stinner12bab6d2011-10-01 01:53:49 +020010493 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010495 if (PyUnicode_CheckExact(self)) {
10496 Py_INCREF(self);
10497 return self;
10498 }
10499 else
10500 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 }
10502
Victor Stinner12bab6d2011-10-01 01:53:49 +020010503 length = end - start;
10504 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010505 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506
Victor Stinnerde636f32011-10-01 03:55:54 +020010507 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010508 PyErr_SetString(PyExc_IndexError, "string index out of range");
10509 return NULL;
10510 }
10511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 kind = PyUnicode_KIND(self);
10513 data = PyUnicode_1BYTE_DATA(self);
Victor Stinner034f6cf2011-09-30 02:26:44 +020010514 return PyUnicode_FromKindAndData(kind,
10515 data + PyUnicode_KIND_SIZE(kind, start),
Victor Stinner12bab6d2011-10-01 01:53:49 +020010516 length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517}
Guido van Rossumd57fd912000-03-10 22:53:23 +000010518
10519static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010520do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010521{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 int kind;
10523 void *data;
10524 Py_ssize_t len, i, j;
10525
10526 if (PyUnicode_READY(self) == -1)
10527 return NULL;
10528
10529 kind = PyUnicode_KIND(self);
10530 data = PyUnicode_DATA(self);
10531 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010532
Benjamin Peterson14339b62009-01-31 16:36:08 +000010533 i = 0;
10534 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010536 i++;
10537 }
10538 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010539
Benjamin Peterson14339b62009-01-31 16:36:08 +000010540 j = len;
10541 if (striptype != LEFTSTRIP) {
10542 do {
10543 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010545 j++;
10546 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010547
Victor Stinner12bab6d2011-10-01 01:53:49 +020010548 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549}
10550
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010551
10552static PyObject *
10553do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
10554{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010555 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010556
Benjamin Peterson14339b62009-01-31 16:36:08 +000010557 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
10558 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010559
Benjamin Peterson14339b62009-01-31 16:36:08 +000010560 if (sep != NULL && sep != Py_None) {
10561 if (PyUnicode_Check(sep))
10562 return _PyUnicode_XStrip(self, striptype, sep);
10563 else {
10564 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010565 "%s arg must be None or str",
10566 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010567 return NULL;
10568 }
10569 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010570
Benjamin Peterson14339b62009-01-31 16:36:08 +000010571 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010572}
10573
10574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010575PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010576 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010577\n\
10578Return a copy of the string S with leading and trailing\n\
10579whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010580If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010581
10582static PyObject *
10583unicode_strip(PyUnicodeObject *self, PyObject *args)
10584{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010585 if (PyTuple_GET_SIZE(args) == 0)
10586 return do_strip(self, BOTHSTRIP); /* Common case */
10587 else
10588 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010589}
10590
10591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010592PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010593 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010594\n\
10595Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010596If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010597
10598static PyObject *
10599unicode_lstrip(PyUnicodeObject *self, PyObject *args)
10600{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010601 if (PyTuple_GET_SIZE(args) == 0)
10602 return do_strip(self, LEFTSTRIP); /* Common case */
10603 else
10604 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010605}
10606
10607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010608PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010609 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010610\n\
10611Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010612If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010613
10614static PyObject *
10615unicode_rstrip(PyUnicodeObject *self, PyObject *args)
10616{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010617 if (PyTuple_GET_SIZE(args) == 0)
10618 return do_strip(self, RIGHTSTRIP); /* Common case */
10619 else
10620 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010621}
10622
10623
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000010625unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626{
10627 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629
Georg Brandl222de0f2009-04-12 12:01:50 +000010630 if (len < 1) {
10631 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020010632 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000010633 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
Tim Peters7a29bd52001-09-12 03:03:31 +000010635 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 /* no repeat, return original string */
10637 Py_INCREF(str);
10638 return (PyObject*) str;
10639 }
Tim Peters8f422462000-09-09 06:13:41 +000010640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 if (PyUnicode_READY(str) == -1)
10642 return NULL;
10643
Victor Stinnerc759f3e2011-10-01 03:09:58 +020010644 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020010645 PyErr_SetString(PyExc_OverflowError,
10646 "repeated string is too long");
10647 return NULL;
10648 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020010650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652 if (!u)
10653 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020010654 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 if (PyUnicode_GET_LENGTH(str) == 1) {
10657 const int kind = PyUnicode_KIND(str);
10658 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
10659 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020010660 if (kind == PyUnicode_1BYTE_KIND)
10661 memset(to, (unsigned char)fill_char, len);
10662 else {
10663 for (n = 0; n < len; ++n)
10664 PyUnicode_WRITE(kind, to, n, fill_char);
10665 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 }
10667 else {
10668 /* number of characters copied this far */
10669 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
10670 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
10671 char *to = (char *) PyUnicode_DATA(u);
10672 Py_MEMCPY(to, PyUnicode_DATA(str),
10673 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000010674 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 n = (done <= nchars-done) ? done : nchars-done;
10676 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010677 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000010678 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010679 }
10680
10681 return (PyObject*) u;
10682}
10683
Alexander Belopolsky40018472011-02-26 01:02:56 +000010684PyObject *
10685PyUnicode_Replace(PyObject *obj,
10686 PyObject *subobj,
10687 PyObject *replobj,
10688 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689{
10690 PyObject *self;
10691 PyObject *str1;
10692 PyObject *str2;
10693 PyObject *result;
10694
10695 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010696 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010698 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010699 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 Py_DECREF(self);
10701 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010702 }
10703 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010704 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010705 Py_DECREF(self);
10706 Py_DECREF(str1);
10707 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710 Py_DECREF(self);
10711 Py_DECREF(str1);
10712 Py_DECREF(str2);
10713 return result;
10714}
10715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010716PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000010717 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718\n\
10719Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000010720old replaced by new. If the optional argument count is\n\
10721given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722
10723static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 PyObject *str1;
10727 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010728 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010729 PyObject *result;
10730
Martin v. Löwis18e16552006-02-15 17:27:45 +000010731 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010734 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 str1 = PyUnicode_FromObject(str1);
10736 if (str1 == NULL || PyUnicode_READY(str1) == -1)
10737 return NULL;
10738 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020010739 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010740 Py_DECREF(str1);
10741 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000010742 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743
10744 result = replace(self, str1, str2, maxcount);
10745
10746 Py_DECREF(str1);
10747 Py_DECREF(str2);
10748 return result;
10749}
10750
Alexander Belopolsky40018472011-02-26 01:02:56 +000010751static PyObject *
10752unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753{
Walter Dörwald79e913e2007-05-12 11:08:06 +000010754 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010755 Py_ssize_t isize;
10756 Py_ssize_t osize, squote, dquote, i, o;
10757 Py_UCS4 max, quote;
10758 int ikind, okind;
10759 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000010760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000010762 return NULL;
10763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 isize = PyUnicode_GET_LENGTH(unicode);
10765 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 /* Compute length of output, quote characters, and
10768 maximum character */
10769 osize = 2; /* quotes */
10770 max = 127;
10771 squote = dquote = 0;
10772 ikind = PyUnicode_KIND(unicode);
10773 for (i = 0; i < isize; i++) {
10774 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
10775 switch (ch) {
10776 case '\'': squote++; osize++; break;
10777 case '"': dquote++; osize++; break;
10778 case '\\': case '\t': case '\r': case '\n':
10779 osize += 2; break;
10780 default:
10781 /* Fast-path ASCII */
10782 if (ch < ' ' || ch == 0x7f)
10783 osize += 4; /* \xHH */
10784 else if (ch < 0x7f)
10785 osize++;
10786 else if (Py_UNICODE_ISPRINTABLE(ch)) {
10787 osize++;
10788 max = ch > max ? ch : max;
10789 }
10790 else if (ch < 0x100)
10791 osize += 4; /* \xHH */
10792 else if (ch < 0x10000)
10793 osize += 6; /* \uHHHH */
10794 else
10795 osize += 10; /* \uHHHHHHHH */
10796 }
10797 }
10798
10799 quote = '\'';
10800 if (squote) {
10801 if (dquote)
10802 /* Both squote and dquote present. Use squote,
10803 and escape them */
10804 osize += squote;
10805 else
10806 quote = '"';
10807 }
10808
10809 repr = PyUnicode_New(osize, max);
10810 if (repr == NULL)
10811 return NULL;
10812 okind = PyUnicode_KIND(repr);
10813 odata = PyUnicode_DATA(repr);
10814
10815 PyUnicode_WRITE(okind, odata, 0, quote);
10816 PyUnicode_WRITE(okind, odata, osize-1, quote);
10817
10818 for (i = 0, o = 1; i < isize; i++) {
10819 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010820
10821 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010822 if ((ch == quote) || (ch == '\\')) {
10823 PyUnicode_WRITE(okind, odata, o++, '\\');
10824 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010825 continue;
10826 }
10827
Benjamin Peterson29060642009-01-31 22:14:21 +000010828 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000010829 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010830 PyUnicode_WRITE(okind, odata, o++, '\\');
10831 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010832 }
10833 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010834 PyUnicode_WRITE(okind, odata, o++, '\\');
10835 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010836 }
10837 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 PyUnicode_WRITE(okind, odata, o++, '\\');
10839 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000010840 }
10841
10842 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000010843 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 PyUnicode_WRITE(okind, odata, o++, '\\');
10845 PyUnicode_WRITE(okind, odata, o++, 'x');
10846 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
10847 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000010848 }
10849
Georg Brandl559e5d72008-06-11 18:37:52 +000010850 /* Copy ASCII characters as-is */
10851 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010852 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000010853 }
10854
Benjamin Peterson29060642009-01-31 22:14:21 +000010855 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000010856 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010857 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000010858 (categories Z* and C* except ASCII space)
10859 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010860 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010861 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010862 if (ch <= 0xff) {
10863 PyUnicode_WRITE(okind, odata, o++, '\\');
10864 PyUnicode_WRITE(okind, odata, o++, 'x');
10865 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
10866 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010867 }
10868 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010869 else if (ch >= 0x10000) {
10870 PyUnicode_WRITE(okind, odata, o++, '\\');
10871 PyUnicode_WRITE(okind, odata, o++, 'U');
10872 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
10873 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
10874 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
10875 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
10876 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
10877 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
10878 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
10879 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010880 }
10881 /* Map 16-bit characters to '\uxxxx' */
10882 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010883 PyUnicode_WRITE(okind, odata, o++, '\\');
10884 PyUnicode_WRITE(okind, odata, o++, 'u');
10885 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
10886 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
10887 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
10888 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000010889 }
10890 }
10891 /* Copy characters as-is */
10892 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000010894 }
10895 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000010896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010897 /* Closing quote already added at the beginning */
Walter Dörwald79e913e2007-05-12 11:08:06 +000010898 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899}
10900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010901PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010902 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903\n\
10904Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010905such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906arguments start and end are interpreted as in slice notation.\n\
10907\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010908Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909
10910static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010911unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912{
Jesus Ceaac451502011-04-20 17:09:23 +020010913 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010914 Py_ssize_t start;
10915 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010916 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917
Jesus Ceaac451502011-04-20 17:09:23 +020010918 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
10919 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000010920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010922 if (PyUnicode_READY(self) == -1)
10923 return NULL;
10924 if (PyUnicode_READY(substring) == -1)
10925 return NULL;
10926
10927 result = any_find_slice(
10928 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
10929 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010930 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931
10932 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010933
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010934 if (result == -2)
10935 return NULL;
10936
Christian Heimes217cfd12007-12-02 14:31:20 +000010937 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938}
10939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010940PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010941 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010943Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944
10945static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010947{
Jesus Ceaac451502011-04-20 17:09:23 +020010948 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010949 Py_ssize_t start;
10950 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010951 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952
Jesus Ceaac451502011-04-20 17:09:23 +020010953 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
10954 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000010955 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 if (PyUnicode_READY(self) == -1)
10958 return NULL;
10959 if (PyUnicode_READY(substring) == -1)
10960 return NULL;
10961
10962 result = any_find_slice(
10963 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
10964 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010965 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010966
10967 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 if (result == -2)
10970 return NULL;
10971
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972 if (result < 0) {
10973 PyErr_SetString(PyExc_ValueError, "substring not found");
10974 return NULL;
10975 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976
Christian Heimes217cfd12007-12-02 14:31:20 +000010977 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978}
10979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010980PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010981 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010983Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010984done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985
10986static PyObject *
10987unicode_rjust(PyUnicodeObject *self, PyObject *args)
10988{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010989 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990 Py_UCS4 fillchar = ' ';
10991
Victor Stinnere9a29352011-10-01 02:14:59 +020010992 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010994
Victor Stinnere9a29352011-10-01 02:14:59 +020010995 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996 return NULL;
10997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010998 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 Py_INCREF(self);
11000 return (PyObject*) self;
11001 }
11002
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011003 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004}
11005
Alexander Belopolsky40018472011-02-26 01:02:56 +000011006PyObject *
11007PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008{
11009 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011010
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011 s = PyUnicode_FromObject(s);
11012 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011013 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011014 if (sep != NULL) {
11015 sep = PyUnicode_FromObject(sep);
11016 if (sep == NULL) {
11017 Py_DECREF(s);
11018 return NULL;
11019 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020 }
11021
11022 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11023
11024 Py_DECREF(s);
11025 Py_XDECREF(sep);
11026 return result;
11027}
11028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011029PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011030 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031\n\
11032Return a list of the words in S, using sep as the\n\
11033delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011034splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011035whitespace string is a separator and empty strings are\n\
11036removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037
11038static PyObject*
11039unicode_split(PyUnicodeObject *self, PyObject *args)
11040{
11041 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011042 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043
Martin v. Löwis18e16552006-02-15 17:27:45 +000011044 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045 return NULL;
11046
11047 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011050 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011052 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053}
11054
Thomas Wouters477c8d52006-05-27 19:21:47 +000011055PyObject *
11056PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11057{
11058 PyObject* str_obj;
11059 PyObject* sep_obj;
11060 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 int kind1, kind2, kind;
11062 void *buf1 = NULL, *buf2 = NULL;
11063 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011064
11065 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011066 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011067 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011068 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011070 Py_DECREF(str_obj);
11071 return NULL;
11072 }
11073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 kind1 = PyUnicode_KIND(str_in);
11075 kind2 = PyUnicode_KIND(sep_obj);
11076 kind = kind1 > kind2 ? kind1 : kind2;
11077 buf1 = PyUnicode_DATA(str_in);
11078 if (kind1 != kind)
11079 buf1 = _PyUnicode_AsKind(str_in, kind);
11080 if (!buf1)
11081 goto onError;
11082 buf2 = PyUnicode_DATA(sep_obj);
11083 if (kind2 != kind)
11084 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11085 if (!buf2)
11086 goto onError;
11087 len1 = PyUnicode_GET_LENGTH(str_obj);
11088 len2 = PyUnicode_GET_LENGTH(sep_obj);
11089
11090 switch(PyUnicode_KIND(str_in)) {
11091 case PyUnicode_1BYTE_KIND:
11092 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11093 break;
11094 case PyUnicode_2BYTE_KIND:
11095 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11096 break;
11097 case PyUnicode_4BYTE_KIND:
11098 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11099 break;
11100 default:
11101 assert(0);
11102 out = 0;
11103 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011104
11105 Py_DECREF(sep_obj);
11106 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011107 if (kind1 != kind)
11108 PyMem_Free(buf1);
11109 if (kind2 != kind)
11110 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011111
11112 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011113 onError:
11114 Py_DECREF(sep_obj);
11115 Py_DECREF(str_obj);
11116 if (kind1 != kind && buf1)
11117 PyMem_Free(buf1);
11118 if (kind2 != kind && buf2)
11119 PyMem_Free(buf2);
11120 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011121}
11122
11123
11124PyObject *
11125PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11126{
11127 PyObject* str_obj;
11128 PyObject* sep_obj;
11129 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130 int kind1, kind2, kind;
11131 void *buf1 = NULL, *buf2 = NULL;
11132 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011133
11134 str_obj = PyUnicode_FromObject(str_in);
11135 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011136 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011137 sep_obj = PyUnicode_FromObject(sep_in);
11138 if (!sep_obj) {
11139 Py_DECREF(str_obj);
11140 return NULL;
11141 }
11142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 kind1 = PyUnicode_KIND(str_in);
11144 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011145 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011146 buf1 = PyUnicode_DATA(str_in);
11147 if (kind1 != kind)
11148 buf1 = _PyUnicode_AsKind(str_in, kind);
11149 if (!buf1)
11150 goto onError;
11151 buf2 = PyUnicode_DATA(sep_obj);
11152 if (kind2 != kind)
11153 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11154 if (!buf2)
11155 goto onError;
11156 len1 = PyUnicode_GET_LENGTH(str_obj);
11157 len2 = PyUnicode_GET_LENGTH(sep_obj);
11158
11159 switch(PyUnicode_KIND(str_in)) {
11160 case PyUnicode_1BYTE_KIND:
11161 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11162 break;
11163 case PyUnicode_2BYTE_KIND:
11164 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11165 break;
11166 case PyUnicode_4BYTE_KIND:
11167 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11168 break;
11169 default:
11170 assert(0);
11171 out = 0;
11172 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011173
11174 Py_DECREF(sep_obj);
11175 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 if (kind1 != kind)
11177 PyMem_Free(buf1);
11178 if (kind2 != kind)
11179 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011180
11181 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 onError:
11183 Py_DECREF(sep_obj);
11184 Py_DECREF(str_obj);
11185 if (kind1 != kind && buf1)
11186 PyMem_Free(buf1);
11187 if (kind2 != kind && buf2)
11188 PyMem_Free(buf2);
11189 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011190}
11191
11192PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011193 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011194\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011195Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011196the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011197found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011198
11199static PyObject*
11200unicode_partition(PyUnicodeObject *self, PyObject *separator)
11201{
11202 return PyUnicode_Partition((PyObject *)self, separator);
11203}
11204
11205PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011206 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011207\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011208Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011209the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011210separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011211
11212static PyObject*
11213unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
11214{
11215 return PyUnicode_RPartition((PyObject *)self, separator);
11216}
11217
Alexander Belopolsky40018472011-02-26 01:02:56 +000011218PyObject *
11219PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011220{
11221 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011222
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011223 s = PyUnicode_FromObject(s);
11224 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011225 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 if (sep != NULL) {
11227 sep = PyUnicode_FromObject(sep);
11228 if (sep == NULL) {
11229 Py_DECREF(s);
11230 return NULL;
11231 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011232 }
11233
11234 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11235
11236 Py_DECREF(s);
11237 Py_XDECREF(sep);
11238 return result;
11239}
11240
11241PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011242 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011243\n\
11244Return a list of the words in S, using sep as the\n\
11245delimiter string, starting at the end of the string and\n\
11246working to the front. If maxsplit is given, at most maxsplit\n\
11247splits are done. If sep is not specified, any whitespace string\n\
11248is a separator.");
11249
11250static PyObject*
11251unicode_rsplit(PyUnicodeObject *self, PyObject *args)
11252{
11253 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011254 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011255
Martin v. Löwis18e16552006-02-15 17:27:45 +000011256 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011257 return NULL;
11258
11259 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011261 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011263 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011264 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011265}
11266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011267PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269\n\
11270Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000011271Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011272is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273
11274static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011275unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011277 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000011278 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011280 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
11281 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282 return NULL;
11283
Guido van Rossum86662912000-04-11 15:38:46 +000011284 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285}
11286
11287static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000011288PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289{
Walter Dörwald346737f2007-05-31 10:44:43 +000011290 if (PyUnicode_CheckExact(self)) {
11291 Py_INCREF(self);
11292 return self;
11293 } else
11294 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020011295 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296}
11297
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011298PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300\n\
11301Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011302and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303
11304static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011305unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307 return fixup(self, fixswapcase);
11308}
11309
Georg Brandlceee0772007-11-27 23:48:05 +000011310PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011312\n\
11313Return a translation table usable for str.translate().\n\
11314If there is only one argument, it must be a dictionary mapping Unicode\n\
11315ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011316Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011317If there are two arguments, they must be strings of equal length, and\n\
11318in the resulting dictionary, each character in x will be mapped to the\n\
11319character at the same position in y. If there is a third argument, it\n\
11320must be a string, whose characters will be mapped to None in the result.");
11321
11322static PyObject*
11323unicode_maketrans(PyUnicodeObject *null, PyObject *args)
11324{
11325 PyObject *x, *y = NULL, *z = NULL;
11326 PyObject *new = NULL, *key, *value;
11327 Py_ssize_t i = 0;
11328 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011329
Georg Brandlceee0772007-11-27 23:48:05 +000011330 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
11331 return NULL;
11332 new = PyDict_New();
11333 if (!new)
11334 return NULL;
11335 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 int x_kind, y_kind, z_kind;
11337 void *x_data, *y_data, *z_data;
11338
Georg Brandlceee0772007-11-27 23:48:05 +000011339 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000011340 if (!PyUnicode_Check(x)) {
11341 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
11342 "be a string if there is a second argument");
11343 goto err;
11344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011346 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
11347 "arguments must have equal length");
11348 goto err;
11349 }
11350 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 x_kind = PyUnicode_KIND(x);
11352 y_kind = PyUnicode_KIND(y);
11353 x_data = PyUnicode_DATA(x);
11354 y_data = PyUnicode_DATA(y);
11355 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
11356 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
11357 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011358 if (!key || !value)
11359 goto err;
11360 res = PyDict_SetItem(new, key, value);
11361 Py_DECREF(key);
11362 Py_DECREF(value);
11363 if (res < 0)
11364 goto err;
11365 }
11366 /* create entries for deleting chars in z */
11367 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 z_kind = PyUnicode_KIND(z);
11369 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000011370 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011372 if (!key)
11373 goto err;
11374 res = PyDict_SetItem(new, key, Py_None);
11375 Py_DECREF(key);
11376 if (res < 0)
11377 goto err;
11378 }
11379 }
11380 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381 int kind;
11382 void *data;
11383
Georg Brandlceee0772007-11-27 23:48:05 +000011384 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000011385 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011386 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
11387 "to maketrans it must be a dict");
11388 goto err;
11389 }
11390 /* copy entries into the new dict, converting string keys to int keys */
11391 while (PyDict_Next(x, &i, &key, &value)) {
11392 if (PyUnicode_Check(key)) {
11393 /* convert string keys to integer keys */
11394 PyObject *newkey;
11395 if (PyUnicode_GET_SIZE(key) != 1) {
11396 PyErr_SetString(PyExc_ValueError, "string keys in translate "
11397 "table must be of length 1");
11398 goto err;
11399 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400 kind = PyUnicode_KIND(key);
11401 data = PyUnicode_DATA(key);
11402 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000011403 if (!newkey)
11404 goto err;
11405 res = PyDict_SetItem(new, newkey, value);
11406 Py_DECREF(newkey);
11407 if (res < 0)
11408 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000011409 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011410 /* just keep integer keys */
11411 if (PyDict_SetItem(new, key, value) < 0)
11412 goto err;
11413 } else {
11414 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
11415 "be strings or integers");
11416 goto err;
11417 }
11418 }
11419 }
11420 return new;
11421 err:
11422 Py_DECREF(new);
11423 return NULL;
11424}
11425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011427 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428\n\
11429Return a copy of the string S, where all characters have been mapped\n\
11430through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011431Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000011432Unmapped characters are left untouched. Characters mapped to None\n\
11433are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
11435static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439}
11440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011441PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011444Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445
11446static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011447unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 return fixup(self, fixupper);
11450}
11451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011452PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000011455Pad a numeric string S with zeros on the left, to fill a field\n\
11456of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
11458static PyObject *
11459unicode_zfill(PyUnicodeObject *self, PyObject *args)
11460{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011461 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462 PyUnicodeObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011463 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 int kind;
11465 void *data;
11466 Py_UCS4 chr;
11467
11468 if (PyUnicode_READY(self) == -1)
11469 return NULL;
11470
Martin v. Löwis18e16552006-02-15 17:27:45 +000011471 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 return NULL;
11473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000011475 if (PyUnicode_CheckExact(self)) {
11476 Py_INCREF(self);
11477 return (PyObject*) self;
11478 }
11479 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020011480 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 }
11482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
11485 u = pad(self, fill, 0, '0');
11486
Walter Dörwald068325e2002-04-15 13:36:47 +000011487 if (u == NULL)
11488 return NULL;
11489
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 kind = PyUnicode_KIND(u);
11491 data = PyUnicode_DATA(u);
11492 chr = PyUnicode_READ(kind, data, fill);
11493
11494 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 PyUnicode_WRITE(kind, data, 0, chr);
11497 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 }
11499
11500 return (PyObject*) u;
11501}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502
11503#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011504static PyObject *
11505unicode__decimal2ascii(PyObject *self)
11506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011508}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509#endif
11510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011511PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011514Return True if S starts with the specified prefix, False otherwise.\n\
11515With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011516With optional end, stop comparing S at that position.\n\
11517prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518
11519static PyObject *
11520unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011521 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011523 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011525 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011526 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011527 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528
Jesus Ceaac451502011-04-20 17:09:23 +020011529 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011530 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011531 if (PyTuple_Check(subobj)) {
11532 Py_ssize_t i;
11533 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11534 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011536 if (substring == NULL)
11537 return NULL;
11538 result = tailmatch(self, substring, start, end, -1);
11539 Py_DECREF(substring);
11540 if (result) {
11541 Py_RETURN_TRUE;
11542 }
11543 }
11544 /* nothing matched */
11545 Py_RETURN_FALSE;
11546 }
11547 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011548 if (substring == NULL) {
11549 if (PyErr_ExceptionMatches(PyExc_TypeError))
11550 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
11551 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011553 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011554 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011556 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557}
11558
11559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011560PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011563Return True if S ends with the specified suffix, False otherwise.\n\
11564With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011565With optional end, stop comparing S at that position.\n\
11566suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567
11568static PyObject *
11569unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011572 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011574 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011575 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011576 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577
Jesus Ceaac451502011-04-20 17:09:23 +020011578 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011580 if (PyTuple_Check(subobj)) {
11581 Py_ssize_t i;
11582 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11583 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011585 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011586 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011587 result = tailmatch(self, substring, start, end, +1);
11588 Py_DECREF(substring);
11589 if (result) {
11590 Py_RETURN_TRUE;
11591 }
11592 }
11593 Py_RETURN_FALSE;
11594 }
11595 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011596 if (substring == NULL) {
11597 if (PyErr_ExceptionMatches(PyExc_TypeError))
11598 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
11599 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011600 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011601 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011602 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011604 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605}
11606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000011608
11609PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011610 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011611\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011612Return a formatted version of S, using substitutions from args and kwargs.\n\
11613The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000011614
Eric Smith27bbca62010-11-04 17:06:58 +000011615PyDoc_STRVAR(format_map__doc__,
11616 "S.format_map(mapping) -> str\n\
11617\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011618Return a formatted version of S, using substitutions from mapping.\n\
11619The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000011620
Eric Smith4a7d76d2008-05-30 18:10:19 +000011621static PyObject *
11622unicode__format__(PyObject* self, PyObject* args)
11623{
11624 PyObject *format_spec;
11625
11626 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
11627 return NULL;
11628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 return _PyUnicode_FormatAdvanced(self, format_spec, 0,
11630 PyUnicode_GET_LENGTH(format_spec));
Eric Smith4a7d76d2008-05-30 18:10:19 +000011631}
11632
Eric Smith8c663262007-08-25 02:26:07 +000011633PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011635\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011636Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000011637
11638static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011639unicode__sizeof__(PyUnicodeObject *v)
11640{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 Py_ssize_t size;
11642
11643 /* If it's a compact object, account for base structure +
11644 character data. */
11645 if (PyUnicode_IS_COMPACT_ASCII(v))
11646 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
11647 else if (PyUnicode_IS_COMPACT(v))
11648 size = sizeof(PyCompactUnicodeObject) +
11649 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
11650 else {
11651 /* If it is a two-block object, account for base object, and
11652 for character block if present. */
11653 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020011654 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 size += (PyUnicode_GET_LENGTH(v) + 1) *
11656 PyUnicode_CHARACTER_SIZE(v);
11657 }
11658 /* If the wstr pointer is present, account for it unless it is shared
11659 with the data pointer. Since PyUnicode_DATA will crash if the object
11660 is not ready, check whether it's either not ready (in which case the
11661 data is entirely in wstr) or if the data is not shared. */
11662 if (_PyUnicode_WSTR(v) &&
11663 (!PyUnicode_IS_READY(v) ||
11664 (PyUnicode_DATA(v) != _PyUnicode_WSTR(v))))
11665 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinnere90fe6a2011-10-01 16:48:13 +020011666 if (!PyUnicode_IS_COMPACT_ASCII(v)
11667 && _PyUnicode_UTF8(v)
11668 && _PyUnicode_UTF8(v) != PyUnicode_DATA(v))
11669 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670
11671 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011672}
11673
11674PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011675 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011676
11677static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020011678unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011679{
Victor Stinner034f6cf2011-09-30 02:26:44 +020011680 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (!copy)
11682 return NULL;
11683 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011684}
11685
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686static PyMethodDef unicode_methods[] = {
11687
11688 /* Order is according to common usage: often used methods should
11689 appear first, since lookup is done sequentially. */
11690
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000011691 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011692 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
11693 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011694 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011695 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
11696 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
11697 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
11698 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
11699 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
11700 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
11701 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011702 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011703 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
11704 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
11705 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011706 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011707 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
11708 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
11709 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011710 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011711 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011712 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011713 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011714 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
11715 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
11716 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
11717 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
11718 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
11719 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
11720 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
11721 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
11722 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
11723 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
11724 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
11725 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
11726 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
11727 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000011728 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000011729 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011730 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000011731 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000011732 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000011733 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000011734 {"maketrans", (PyCFunction) unicode_maketrans,
11735 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011736 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000011737#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011738 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739#endif
11740
11741#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011742 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011743 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744#endif
11745
Benjamin Peterson14339b62009-01-31 16:36:08 +000011746 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747 {NULL, NULL}
11748};
11749
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011750static PyObject *
11751unicode_mod(PyObject *v, PyObject *w)
11752{
Brian Curtindfc80e32011-08-10 20:28:54 -050011753 if (!PyUnicode_Check(v))
11754 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011756}
11757
11758static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011759 0, /*nb_add*/
11760 0, /*nb_subtract*/
11761 0, /*nb_multiply*/
11762 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000011763};
11764
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011766 (lenfunc) unicode_length, /* sq_length */
11767 PyUnicode_Concat, /* sq_concat */
11768 (ssizeargfunc) unicode_repeat, /* sq_repeat */
11769 (ssizeargfunc) unicode_getitem, /* sq_item */
11770 0, /* sq_slice */
11771 0, /* sq_ass_item */
11772 0, /* sq_ass_slice */
11773 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774};
11775
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011776static PyObject*
11777unicode_subscript(PyUnicodeObject* self, PyObject* item)
11778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 if (PyUnicode_READY(self) == -1)
11780 return NULL;
11781
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011782 if (PyIndex_Check(item)) {
11783 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011784 if (i == -1 && PyErr_Occurred())
11785 return NULL;
11786 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011788 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011789 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000011790 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 const Py_UNICODE* source_buf;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011792 Py_UNICODE* result_buf;
11793 PyObject* result;
11794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000011796 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011797 return NULL;
11798 }
11799
11800 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 return PyUnicode_New(0, 0);
11802 } else if (start == 0 && step == 1 &&
11803 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000011804 PyUnicode_CheckExact(self)) {
11805 Py_INCREF(self);
11806 return (PyObject *)self;
11807 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011808 return PyUnicode_Substring((PyObject*)self,
11809 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011810 } else {
11811 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +000011812 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
11813 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011814
Benjamin Peterson29060642009-01-31 22:14:21 +000011815 if (result_buf == NULL)
11816 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011817
11818 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
11819 result_buf[i] = source_buf[cur];
11820 }
Tim Petersced69f82003-09-16 20:30:58 +000011821
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011822 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +000011823 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011824 return result;
11825 }
11826 } else {
11827 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
11828 return NULL;
11829 }
11830}
11831
11832static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011833 (lenfunc)unicode_length, /* mp_length */
11834 (binaryfunc)unicode_subscript, /* mp_subscript */
11835 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000011836};
11837
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838
Guido van Rossumd57fd912000-03-10 22:53:23 +000011839/* Helpers for PyUnicode_Format() */
11840
11841static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000011842getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011844 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 (*p_argidx)++;
11847 if (arglen < 0)
11848 return args;
11849 else
11850 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851 }
11852 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011853 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 return NULL;
11855}
11856
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011857/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011859static PyObject *
11860formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011862 char *p;
11863 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864 double x;
Tim Petersced69f82003-09-16 20:30:58 +000011865
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866 x = PyFloat_AsDouble(v);
11867 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011868 return NULL;
11869
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011871 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000011872
Eric Smith0923d1d2009-04-16 20:16:10 +000011873 p = PyOS_double_to_string(x, type, prec,
11874 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011875 if (p == NULL)
11876 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000011878 PyMem_Free(p);
11879 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880}
11881
Tim Peters38fd5b62000-09-21 05:43:11 +000011882static PyObject*
11883formatlong(PyObject *val, int flags, int prec, int type)
11884{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011885 char *buf;
11886 int len;
11887 PyObject *str; /* temporary string object. */
11888 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000011889
Benjamin Peterson14339b62009-01-31 16:36:08 +000011890 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
11891 if (!str)
11892 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011894 Py_DECREF(str);
11895 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000011896}
11897
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899formatchar(Py_UCS4 *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011900 size_t buflen,
11901 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000011903 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011904 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 if (PyUnicode_GET_LENGTH(v) == 1) {
11906 buf[0] = PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000011907 buf[1] = '\0';
11908 return 1;
11909 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011910 goto onError;
11911 }
11912 else {
11913 /* Integer input truncated to a character */
11914 long x;
11915 x = PyLong_AsLong(v);
11916 if (x == -1 && PyErr_Occurred())
11917 goto onError;
11918
11919 if (x < 0 || x > 0x10ffff) {
11920 PyErr_SetString(PyExc_OverflowError,
11921 "%c arg not in range(0x110000)");
11922 return -1;
11923 }
11924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 buf[0] = (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011926 buf[1] = '\0';
11927 return 1;
11928 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000011929
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011931 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000011933 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934}
11935
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011936/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011937 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011938*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +000011939#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000011940
Alexander Belopolsky40018472011-02-26 01:02:56 +000011941PyObject *
11942PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 void *fmt;
11945 int fmtkind;
11946 PyObject *result;
11947 Py_UCS4 *res, *res0;
11948 Py_UCS4 max;
11949 int kind;
11950 Py_ssize_t fmtcnt, fmtpos, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952 PyObject *dict = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 PyUnicodeObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +000011954
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011956 PyErr_BadInternalCall();
11957 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
11960 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011961 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 fmt = PyUnicode_DATA(uformat);
11963 fmtkind = PyUnicode_KIND(uformat);
11964 fmtcnt = PyUnicode_GET_LENGTH(uformat);
11965 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966
11967 reslen = rescnt = fmtcnt + 100;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 res = res0 = PyMem_Malloc(reslen * sizeof(Py_UCS4));
11969 if (res0 == NULL) {
11970 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973
11974 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011975 arglen = PyTuple_Size(args);
11976 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011977 }
11978 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 arglen = -1;
11980 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981 }
Christian Heimes90aa7642007-12-19 02:45:37 +000011982 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000011983 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000011984 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985
11986 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 if (--rescnt < 0) {
11989 rescnt = fmtcnt + 100;
11990 reslen += rescnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
11992 if (res0 == NULL){
11993 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000011994 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 }
11996 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000011997 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011998 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 *res++ = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012000 }
12001 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 /* Got a format specifier */
12003 int flags = 0;
12004 Py_ssize_t width = -1;
12005 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 Py_UCS4 c = '\0';
12007 Py_UCS4 fill;
Benjamin Peterson29060642009-01-31 22:14:21 +000012008 int isnumok;
12009 PyObject *v = NULL;
12010 PyObject *temp = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 void *pbuf;
12012 Py_ssize_t pindex;
Benjamin Peterson29060642009-01-31 22:14:21 +000012013 Py_UNICODE sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 Py_ssize_t len, len1;
12015 Py_UCS4 formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017 fmtpos++;
12018 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12019 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012020 Py_ssize_t keylen;
12021 PyObject *key;
12022 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012023
Benjamin Peterson29060642009-01-31 22:14:21 +000012024 if (dict == NULL) {
12025 PyErr_SetString(PyExc_TypeError,
12026 "format requires a mapping");
12027 goto onError;
12028 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 /* Skip over balanced parentheses */
12033 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012035 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012037 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012041 if (fmtcnt < 0 || pcount > 0) {
12042 PyErr_SetString(PyExc_ValueError,
12043 "incomplete format key");
12044 goto onError;
12045 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012046 key = PyUnicode_Substring((PyObject*)uformat,
12047 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012048 if (key == NULL)
12049 goto onError;
12050 if (args_owned) {
12051 Py_DECREF(args);
12052 args_owned = 0;
12053 }
12054 args = PyObject_GetItem(dict, key);
12055 Py_DECREF(key);
12056 if (args == NULL) {
12057 goto onError;
12058 }
12059 args_owned = 1;
12060 arglen = -1;
12061 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012062 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012063 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012065 case '-': flags |= F_LJUST; continue;
12066 case '+': flags |= F_SIGN; continue;
12067 case ' ': flags |= F_BLANK; continue;
12068 case '#': flags |= F_ALT; continue;
12069 case '0': flags |= F_ZERO; continue;
12070 }
12071 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012073 if (c == '*') {
12074 v = getnextarg(args, arglen, &argidx);
12075 if (v == NULL)
12076 goto onError;
12077 if (!PyLong_Check(v)) {
12078 PyErr_SetString(PyExc_TypeError,
12079 "* wants int");
12080 goto onError;
12081 }
12082 width = PyLong_AsLong(v);
12083 if (width == -1 && PyErr_Occurred())
12084 goto onError;
12085 if (width < 0) {
12086 flags |= F_LJUST;
12087 width = -width;
12088 }
12089 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012091 }
12092 else if (c >= '0' && c <= '9') {
12093 width = c - '0';
12094 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 if (c < '0' || c > '9')
12097 break;
12098 if ((width*10) / 10 != width) {
12099 PyErr_SetString(PyExc_ValueError,
12100 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012101 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012102 }
12103 width = width*10 + (c - '0');
12104 }
12105 }
12106 if (c == '.') {
12107 prec = 0;
12108 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012110 if (c == '*') {
12111 v = getnextarg(args, arglen, &argidx);
12112 if (v == NULL)
12113 goto onError;
12114 if (!PyLong_Check(v)) {
12115 PyErr_SetString(PyExc_TypeError,
12116 "* wants int");
12117 goto onError;
12118 }
12119 prec = PyLong_AsLong(v);
12120 if (prec == -1 && PyErr_Occurred())
12121 goto onError;
12122 if (prec < 0)
12123 prec = 0;
12124 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 }
12127 else if (c >= '0' && c <= '9') {
12128 prec = c - '0';
12129 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012131 if (c < '0' || c > '9')
12132 break;
12133 if ((prec*10) / 10 != prec) {
12134 PyErr_SetString(PyExc_ValueError,
12135 "prec too big");
12136 goto onError;
12137 }
12138 prec = prec*10 + (c - '0');
12139 }
12140 }
12141 } /* prec */
12142 if (fmtcnt >= 0) {
12143 if (c == 'h' || c == 'l' || c == 'L') {
12144 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012146 }
12147 }
12148 if (fmtcnt < 0) {
12149 PyErr_SetString(PyExc_ValueError,
12150 "incomplete format");
12151 goto onError;
12152 }
12153 if (c != '%') {
12154 v = getnextarg(args, arglen, &argidx);
12155 if (v == NULL)
12156 goto onError;
12157 }
12158 sign = 0;
12159 fill = ' ';
12160 switch (c) {
12161
12162 case '%':
12163 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012165 /* presume that buffer length is at least 1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 PyUnicode_WRITE(kind, pbuf, 0, '%');
Benjamin Peterson29060642009-01-31 22:14:21 +000012167 len = 1;
12168 break;
12169
12170 case 's':
12171 case 'r':
12172 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012173 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012174 temp = v;
12175 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012176 }
12177 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 if (c == 's')
12179 temp = PyObject_Str(v);
12180 else if (c == 'r')
12181 temp = PyObject_Repr(v);
12182 else
12183 temp = PyObject_ASCII(v);
12184 if (temp == NULL)
12185 goto onError;
12186 if (PyUnicode_Check(temp))
12187 /* nothing to do */;
12188 else {
12189 Py_DECREF(temp);
12190 PyErr_SetString(PyExc_TypeError,
12191 "%s argument has non-string str()");
12192 goto onError;
12193 }
12194 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 if (PyUnicode_READY(temp) == -1) {
12196 Py_CLEAR(temp);
12197 goto onError;
12198 }
12199 pbuf = PyUnicode_DATA(temp);
12200 kind = PyUnicode_KIND(temp);
12201 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012202 if (prec >= 0 && len > prec)
12203 len = prec;
12204 break;
12205
12206 case 'i':
12207 case 'd':
12208 case 'u':
12209 case 'o':
12210 case 'x':
12211 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000012212 isnumok = 0;
12213 if (PyNumber_Check(v)) {
12214 PyObject *iobj=NULL;
12215
12216 if (PyLong_Check(v)) {
12217 iobj = v;
12218 Py_INCREF(iobj);
12219 }
12220 else {
12221 iobj = PyNumber_Long(v);
12222 }
12223 if (iobj!=NULL) {
12224 if (PyLong_Check(iobj)) {
12225 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070012226 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 Py_DECREF(iobj);
12228 if (!temp)
12229 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 if (PyUnicode_READY(temp) == -1) {
12231 Py_CLEAR(temp);
12232 goto onError;
12233 }
12234 pbuf = PyUnicode_DATA(temp);
12235 kind = PyUnicode_KIND(temp);
12236 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012237 sign = 1;
12238 }
12239 else {
12240 Py_DECREF(iobj);
12241 }
12242 }
12243 }
12244 if (!isnumok) {
12245 PyErr_Format(PyExc_TypeError,
12246 "%%%c format: a number is required, "
12247 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
12248 goto onError;
12249 }
12250 if (flags & F_ZERO)
12251 fill = '0';
12252 break;
12253
12254 case 'e':
12255 case 'E':
12256 case 'f':
12257 case 'F':
12258 case 'g':
12259 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012260 temp = formatfloat(v, flags, prec, c);
12261 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000012262 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 if (PyUnicode_READY(temp) == -1) {
12264 Py_CLEAR(temp);
12265 goto onError;
12266 }
12267 pbuf = PyUnicode_DATA(temp);
12268 kind = PyUnicode_KIND(temp);
12269 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 sign = 1;
12271 if (flags & F_ZERO)
12272 fill = '0';
12273 break;
12274
12275 case 'c':
12276 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277 kind = PyUnicode_4BYTE_KIND;
Victor Stinnerb9dcffb2011-09-29 00:39:24 +020012278 len = formatchar(pbuf, Py_ARRAY_LENGTH(formatbuf), v);
Benjamin Peterson29060642009-01-31 22:14:21 +000012279 if (len < 0)
12280 goto onError;
12281 break;
12282
12283 default:
12284 PyErr_Format(PyExc_ValueError,
12285 "unsupported format character '%c' (0x%x) "
12286 "at index %zd",
12287 (31<=c && c<=126) ? (char)c : '?',
12288 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000012290 goto onError;
12291 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 /* pbuf is initialized here. */
12293 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000012294 if (sign) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 if (PyUnicode_READ(kind, pbuf, pindex) == '-' ||
12296 PyUnicode_READ(kind, pbuf, pindex) == '+') {
12297 sign = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012298 len--;
12299 }
12300 else if (flags & F_SIGN)
12301 sign = '+';
12302 else if (flags & F_BLANK)
12303 sign = ' ';
12304 else
12305 sign = 0;
12306 }
12307 if (width < len)
12308 width = len;
12309 if (rescnt - (sign != 0) < width) {
12310 reslen -= rescnt;
12311 rescnt = width + fmtcnt + 100;
12312 reslen += rescnt;
12313 if (reslen < 0) {
12314 Py_XDECREF(temp);
12315 PyErr_NoMemory();
12316 goto onError;
12317 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12319 if (res0 == 0) {
12320 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 Py_XDECREF(temp);
12322 goto onError;
12323 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012325 }
12326 if (sign) {
12327 if (fill != ' ')
12328 *res++ = sign;
12329 rescnt--;
12330 if (width > len)
12331 width--;
12332 }
12333 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12335 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 if (fill != ' ') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12338 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012339 }
12340 rescnt -= 2;
12341 width -= 2;
12342 if (width < 0)
12343 width = 0;
12344 len -= 2;
12345 }
12346 if (width > len && !(flags & F_LJUST)) {
12347 do {
12348 --rescnt;
12349 *res++ = fill;
12350 } while (--width > len);
12351 }
12352 if (fill == ' ') {
12353 if (sign)
12354 *res++ = sign;
12355 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12357 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
12358 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12359 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012360 }
12361 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 /* Copy all characters, preserving len */
12363 len1 = len;
12364 while (len1--) {
12365 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12366 rescnt--;
12367 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012368 while (--width >= len) {
12369 --rescnt;
12370 *res++ = ' ';
12371 }
12372 if (dict && (argidx < arglen) && c != '%') {
12373 PyErr_SetString(PyExc_TypeError,
12374 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +000012375 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 goto onError;
12377 }
12378 Py_XDECREF(temp);
12379 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380 } /* until end */
12381 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012382 PyErr_SetString(PyExc_TypeError,
12383 "not all arguments converted during string formatting");
12384 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385 }
12386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387
12388 for (max=0, res = res0; res < res0+reslen-rescnt; res++)
12389 if (*res > max)
12390 max = *res;
12391 result = PyUnicode_New(reslen - rescnt, max);
12392 if (!result)
Benjamin Peterson29060642009-01-31 22:14:21 +000012393 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 kind = PyUnicode_KIND(result);
12395 for (res = res0; res < res0+reslen-rescnt; res++)
12396 PyUnicode_WRITE(kind, PyUnicode_DATA(result), res-res0, *res);
12397 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012398 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012399 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400 }
12401 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012402 return (PyObject *)result;
12403
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406 Py_DECREF(uformat);
12407 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012408 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409 }
12410 return NULL;
12411}
12412
Jeremy Hylton938ace62002-07-17 16:30:39 +000012413static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000012414unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
12415
Tim Peters6d6c1a32001-08-02 04:15:00 +000012416static PyObject *
12417unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12418{
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012420 static char *kwlist[] = {"object", "encoding", "errors", 0};
12421 char *encoding = NULL;
12422 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000012423
Benjamin Peterson14339b62009-01-31 16:36:08 +000012424 if (type != &PyUnicode_Type)
12425 return unicode_subtype_new(type, args, kwds);
12426 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000012427 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012428 return NULL;
12429 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012430 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012431 if (encoding == NULL && errors == NULL)
12432 return PyObject_Str(x);
12433 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012434 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000012435}
12436
Guido van Rossume023fe02001-08-30 03:12:59 +000012437static PyObject *
12438unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12439{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012440 PyUnicodeObject *unicode, *self;
12441 Py_ssize_t length, char_size;
12442 int share_wstr, share_utf8;
12443 unsigned int kind;
12444 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000012445
Benjamin Peterson14339b62009-01-31 16:36:08 +000012446 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012447
12448 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
12449 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012450 return NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012451 assert(PyUnicode_Check(unicode));
12452 if (PyUnicode_READY(unicode))
12453 return NULL;
12454
12455 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
12456 if (self == NULL) {
12457 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012458 return NULL;
12459 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012460 kind = PyUnicode_KIND(unicode);
12461 length = PyUnicode_GET_LENGTH(unicode);
12462
12463 _PyUnicode_LENGTH(self) = length;
12464 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
12465 _PyUnicode_STATE(self).interned = 0;
12466 _PyUnicode_STATE(self).kind = kind;
12467 _PyUnicode_STATE(self).compact = 0;
12468 _PyUnicode_STATE(self).ascii = 0;
12469 _PyUnicode_STATE(self).ready = 1;
12470 _PyUnicode_WSTR(self) = NULL;
12471 _PyUnicode_UTF8_LENGTH(self) = 0;
12472 _PyUnicode_UTF8(self) = NULL;
12473 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020012474 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012475
12476 share_utf8 = 0;
12477 share_wstr = 0;
12478 if (kind == PyUnicode_1BYTE_KIND) {
12479 char_size = 1;
12480 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
12481 share_utf8 = 1;
12482 }
12483 else if (kind == PyUnicode_2BYTE_KIND) {
12484 char_size = 2;
12485 if (sizeof(wchar_t) == 2)
12486 share_wstr = 1;
12487 }
12488 else {
12489 assert(kind == PyUnicode_4BYTE_KIND);
12490 char_size = 4;
12491 if (sizeof(wchar_t) == 4)
12492 share_wstr = 1;
12493 }
12494
12495 /* Ensure we won't overflow the length. */
12496 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
12497 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012499 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012500 data = PyObject_MALLOC((length + 1) * char_size);
12501 if (data == NULL) {
12502 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 goto onError;
12504 }
12505
Victor Stinnerc3c74152011-10-02 20:39:55 +020012506 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012507 if (share_utf8) {
12508 _PyUnicode_UTF8_LENGTH(self) = length;
12509 _PyUnicode_UTF8(self) = data;
12510 }
12511 if (share_wstr) {
12512 _PyUnicode_WSTR_LENGTH(self) = length;
12513 _PyUnicode_WSTR(self) = (wchar_t *)data;
12514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012516 Py_MEMCPY(data, PyUnicode_DATA(unicode),
12517 PyUnicode_KIND_SIZE(kind, length + 1));
12518 Py_DECREF(unicode);
12519 return (PyObject *)self;
12520
12521onError:
12522 Py_DECREF(unicode);
12523 Py_DECREF(self);
12524 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000012525}
12526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012527PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000012529\n\
Collin Winterd474ce82007-08-07 19:42:11 +000012530Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000012531encoding defaults to the current default string encoding.\n\
12532errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000012533
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012534static PyObject *unicode_iter(PyObject *seq);
12535
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000012537 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012538 "str", /* tp_name */
12539 sizeof(PyUnicodeObject), /* tp_size */
12540 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012542 (destructor)unicode_dealloc, /* tp_dealloc */
12543 0, /* tp_print */
12544 0, /* tp_getattr */
12545 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012546 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012547 unicode_repr, /* tp_repr */
12548 &unicode_as_number, /* tp_as_number */
12549 &unicode_as_sequence, /* tp_as_sequence */
12550 &unicode_as_mapping, /* tp_as_mapping */
12551 (hashfunc) unicode_hash, /* tp_hash*/
12552 0, /* tp_call*/
12553 (reprfunc) unicode_str, /* tp_str */
12554 PyObject_GenericGetAttr, /* tp_getattro */
12555 0, /* tp_setattro */
12556 0, /* tp_as_buffer */
12557 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000012558 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012559 unicode_doc, /* tp_doc */
12560 0, /* tp_traverse */
12561 0, /* tp_clear */
12562 PyUnicode_RichCompare, /* tp_richcompare */
12563 0, /* tp_weaklistoffset */
12564 unicode_iter, /* tp_iter */
12565 0, /* tp_iternext */
12566 unicode_methods, /* tp_methods */
12567 0, /* tp_members */
12568 0, /* tp_getset */
12569 &PyBaseObject_Type, /* tp_base */
12570 0, /* tp_dict */
12571 0, /* tp_descr_get */
12572 0, /* tp_descr_set */
12573 0, /* tp_dictoffset */
12574 0, /* tp_init */
12575 0, /* tp_alloc */
12576 unicode_new, /* tp_new */
12577 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578};
12579
12580/* Initialize the Unicode implementation */
12581
Thomas Wouters78890102000-07-22 19:25:51 +000012582void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012584 int i;
12585
Thomas Wouters477c8d52006-05-27 19:21:47 +000012586 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012588 0x000A, /* LINE FEED */
12589 0x000D, /* CARRIAGE RETURN */
12590 0x001C, /* FILE SEPARATOR */
12591 0x001D, /* GROUP SEPARATOR */
12592 0x001E, /* RECORD SEPARATOR */
12593 0x0085, /* NEXT LINE */
12594 0x2028, /* LINE SEPARATOR */
12595 0x2029, /* PARAGRAPH SEPARATOR */
12596 };
12597
Fred Drakee4315f52000-05-09 19:53:39 +000012598 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020012599 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012600 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012602
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012603 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000012604 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000012605 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012606 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012607
12608 /* initialize the linebreak bloom filter */
12609 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020012611 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012612
12613 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614}
12615
12616/* Finalize the Unicode implementation */
12617
Christian Heimesa156e092008-02-16 07:38:31 +000012618int
12619PyUnicode_ClearFreeList(void)
12620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000012622}
12623
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624void
Thomas Wouters78890102000-07-22 19:25:51 +000012625_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012627 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000012629 Py_XDECREF(unicode_empty);
12630 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000012631
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012632 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012633 if (unicode_latin1[i]) {
12634 Py_DECREF(unicode_latin1[i]);
12635 unicode_latin1[i] = NULL;
12636 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012637 }
Christian Heimesa156e092008-02-16 07:38:31 +000012638 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000012640
Walter Dörwald16807132007-05-25 13:52:07 +000012641void
12642PyUnicode_InternInPlace(PyObject **p)
12643{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012644 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
12645 PyObject *t;
12646 if (s == NULL || !PyUnicode_Check(s))
12647 Py_FatalError(
12648 "PyUnicode_InternInPlace: unicode strings only please!");
12649 /* If it's a subclass, we don't really know what putting
12650 it in the interned dict might do. */
12651 if (!PyUnicode_CheckExact(s))
12652 return;
12653 if (PyUnicode_CHECK_INTERNED(s))
12654 return;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 if (PyUnicode_READY(s) == -1) {
12656 assert(0 && "ready fail in intern...");
12657 return;
12658 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012659 if (interned == NULL) {
12660 interned = PyDict_New();
12661 if (interned == NULL) {
12662 PyErr_Clear(); /* Don't leave an exception */
12663 return;
12664 }
12665 }
12666 /* It might be that the GetItem call fails even
12667 though the key is present in the dictionary,
12668 namely when this happens during a stack overflow. */
12669 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000012670 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012671 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000012672
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 if (t) {
12674 Py_INCREF(t);
12675 Py_DECREF(*p);
12676 *p = t;
12677 return;
12678 }
Walter Dörwald16807132007-05-25 13:52:07 +000012679
Benjamin Peterson14339b62009-01-31 16:36:08 +000012680 PyThreadState_GET()->recursion_critical = 1;
12681 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
12682 PyErr_Clear();
12683 PyThreadState_GET()->recursion_critical = 0;
12684 return;
12685 }
12686 PyThreadState_GET()->recursion_critical = 0;
12687 /* The two references in interned are not counted by refcnt.
12688 The deallocator will take care of this */
12689 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000012691}
12692
12693void
12694PyUnicode_InternImmortal(PyObject **p)
12695{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 PyUnicodeObject *u = (PyUnicodeObject *)*p;
12697
Benjamin Peterson14339b62009-01-31 16:36:08 +000012698 PyUnicode_InternInPlace(p);
12699 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012701 Py_INCREF(*p);
12702 }
Walter Dörwald16807132007-05-25 13:52:07 +000012703}
12704
12705PyObject *
12706PyUnicode_InternFromString(const char *cp)
12707{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012708 PyObject *s = PyUnicode_FromString(cp);
12709 if (s == NULL)
12710 return NULL;
12711 PyUnicode_InternInPlace(&s);
12712 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000012713}
12714
Alexander Belopolsky40018472011-02-26 01:02:56 +000012715void
12716_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000012717{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012718 PyObject *keys;
12719 PyUnicodeObject *s;
12720 Py_ssize_t i, n;
12721 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000012722
Benjamin Peterson14339b62009-01-31 16:36:08 +000012723 if (interned == NULL || !PyDict_Check(interned))
12724 return;
12725 keys = PyDict_Keys(interned);
12726 if (keys == NULL || !PyList_Check(keys)) {
12727 PyErr_Clear();
12728 return;
12729 }
Walter Dörwald16807132007-05-25 13:52:07 +000012730
Benjamin Peterson14339b62009-01-31 16:36:08 +000012731 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
12732 detector, interned unicode strings are not forcibly deallocated;
12733 rather, we give them their stolen references back, and then clear
12734 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000012735
Benjamin Peterson14339b62009-01-31 16:36:08 +000012736 n = PyList_GET_SIZE(keys);
12737 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000012738 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012739 for (i = 0; i < n; i++) {
12740 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012741 if (PyUnicode_READY(s) == -1)
12742 fprintf(stderr, "could not ready string\n");
12743 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012744 case SSTATE_NOT_INTERNED:
12745 /* XXX Shouldn't happen */
12746 break;
12747 case SSTATE_INTERNED_IMMORTAL:
12748 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012750 break;
12751 case SSTATE_INTERNED_MORTAL:
12752 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012754 break;
12755 default:
12756 Py_FatalError("Inconsistent interned string state.");
12757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012759 }
12760 fprintf(stderr, "total size of all interned strings: "
12761 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
12762 "mortal/immortal\n", mortal_size, immortal_size);
12763 Py_DECREF(keys);
12764 PyDict_Clear(interned);
12765 Py_DECREF(interned);
12766 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000012767}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012768
12769
12770/********************* Unicode Iterator **************************/
12771
12772typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012773 PyObject_HEAD
12774 Py_ssize_t it_index;
12775 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012776} unicodeiterobject;
12777
12778static void
12779unicodeiter_dealloc(unicodeiterobject *it)
12780{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012781 _PyObject_GC_UNTRACK(it);
12782 Py_XDECREF(it->it_seq);
12783 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012784}
12785
12786static int
12787unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
12788{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012789 Py_VISIT(it->it_seq);
12790 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012791}
12792
12793static PyObject *
12794unicodeiter_next(unicodeiterobject *it)
12795{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012796 PyUnicodeObject *seq;
12797 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012798
Benjamin Peterson14339b62009-01-31 16:36:08 +000012799 assert(it != NULL);
12800 seq = it->it_seq;
12801 if (seq == NULL)
12802 return NULL;
12803 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012805 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
12806 int kind = PyUnicode_KIND(seq);
12807 void *data = PyUnicode_DATA(seq);
12808 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
12809 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012810 if (item != NULL)
12811 ++it->it_index;
12812 return item;
12813 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012814
Benjamin Peterson14339b62009-01-31 16:36:08 +000012815 Py_DECREF(seq);
12816 it->it_seq = NULL;
12817 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012818}
12819
12820static PyObject *
12821unicodeiter_len(unicodeiterobject *it)
12822{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012823 Py_ssize_t len = 0;
12824 if (it->it_seq)
12825 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
12826 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012827}
12828
12829PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
12830
12831static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012832 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000012834 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012835};
12836
12837PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012838 PyVarObject_HEAD_INIT(&PyType_Type, 0)
12839 "str_iterator", /* tp_name */
12840 sizeof(unicodeiterobject), /* tp_basicsize */
12841 0, /* tp_itemsize */
12842 /* methods */
12843 (destructor)unicodeiter_dealloc, /* tp_dealloc */
12844 0, /* tp_print */
12845 0, /* tp_getattr */
12846 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012847 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012848 0, /* tp_repr */
12849 0, /* tp_as_number */
12850 0, /* tp_as_sequence */
12851 0, /* tp_as_mapping */
12852 0, /* tp_hash */
12853 0, /* tp_call */
12854 0, /* tp_str */
12855 PyObject_GenericGetAttr, /* tp_getattro */
12856 0, /* tp_setattro */
12857 0, /* tp_as_buffer */
12858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
12859 0, /* tp_doc */
12860 (traverseproc)unicodeiter_traverse, /* tp_traverse */
12861 0, /* tp_clear */
12862 0, /* tp_richcompare */
12863 0, /* tp_weaklistoffset */
12864 PyObject_SelfIter, /* tp_iter */
12865 (iternextfunc)unicodeiter_next, /* tp_iternext */
12866 unicodeiter_methods, /* tp_methods */
12867 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012868};
12869
12870static PyObject *
12871unicode_iter(PyObject *seq)
12872{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012873 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012874
Benjamin Peterson14339b62009-01-31 16:36:08 +000012875 if (!PyUnicode_Check(seq)) {
12876 PyErr_BadInternalCall();
12877 return NULL;
12878 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012879 if (PyUnicode_READY(seq) == -1)
12880 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012881 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
12882 if (it == NULL)
12883 return NULL;
12884 it->it_index = 0;
12885 Py_INCREF(seq);
12886 it->it_seq = (PyUnicodeObject *)seq;
12887 _PyObject_GC_TRACK(it);
12888 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012889}
12890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891#define UNIOP(x) Py_UNICODE_##x
12892#define UNIOP_t Py_UNICODE
12893#include "uniops.h"
12894#undef UNIOP
12895#undef UNIOP_t
12896#define UNIOP(x) Py_UCS4_##x
12897#define UNIOP_t Py_UCS4
12898#include "uniops.h"
12899#undef UNIOP
12900#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000012901
Victor Stinner71133ff2010-09-01 23:43:53 +000012902Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000012903PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000012904{
12905 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
12906 Py_UNICODE *copy;
12907 Py_ssize_t size;
12908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 if (!PyUnicode_Check(unicode)) {
12910 PyErr_BadArgument();
12911 return NULL;
12912 }
Victor Stinner71133ff2010-09-01 23:43:53 +000012913 /* Ensure we won't overflow the size. */
12914 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
12915 PyErr_NoMemory();
12916 return NULL;
12917 }
12918 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
12919 size *= sizeof(Py_UNICODE);
12920 copy = PyMem_Malloc(size);
12921 if (copy == NULL) {
12922 PyErr_NoMemory();
12923 return NULL;
12924 }
12925 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
12926 return copy;
12927}
Martin v. Löwis5b222132007-06-10 09:51:05 +000012928
Georg Brandl66c221e2010-10-14 07:04:07 +000012929/* A _string module, to export formatter_parser and formatter_field_name_split
12930 to the string.Formatter class implemented in Python. */
12931
12932static PyMethodDef _string_methods[] = {
12933 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
12934 METH_O, PyDoc_STR("split the argument as a field name")},
12935 {"formatter_parser", (PyCFunction) formatter_parser,
12936 METH_O, PyDoc_STR("parse the argument as a format string")},
12937 {NULL, NULL}
12938};
12939
12940static struct PyModuleDef _string_module = {
12941 PyModuleDef_HEAD_INIT,
12942 "_string",
12943 PyDoc_STR("string helper module"),
12944 0,
12945 _string_methods,
12946 NULL,
12947 NULL,
12948 NULL,
12949 NULL
12950};
12951
12952PyMODINIT_FUNC
12953PyInit__string(void)
12954{
12955 return PyModule_Create(&_string_module);
12956}
12957
12958
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012959#ifdef __cplusplus
12960}
12961#endif