blob: 29788b3c4106c4bd191f6d6c96986cc61cb3ce82 [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 Stinner829c0ad2011-10-03 01:08:02 +0200136/* true if the Unicode object has an allocated UTF-8 memory block
137 (not shared with other data) */
138#define _PyUnicode_HAS_UTF8_MEMORY(op) \
139 (assert(PyUnicode_Check(op)), \
140 (!PyUnicode_IS_COMPACT_ASCII(op) \
141 && _PyUnicode_UTF8(op) \
142 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
143
144
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200145/* The Unicode string has been modified: reset the hash */
146#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
147
Walter Dörwald16807132007-05-25 13:52:07 +0000148/* This dictionary holds all interned unicode strings. Note that references
149 to strings in this dictionary are *not* counted in the string's ob_refcnt.
150 When the interned string reaches a refcnt of 0 the string deallocation
151 function will delete the reference from this dictionary.
152
153 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000154 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000155*/
156static PyObject *interned;
157
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000158/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200159static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000160
161/* Single character Unicode strings in the Latin-1 range are being
162 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200163static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000164
Christian Heimes190d79e2008-01-30 11:58:22 +0000165/* Fast detection of the most frequent whitespace characters */
166const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000167 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000168/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000169/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000170/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000171/* case 0x000C: * FORM FEED */
172/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000173 0, 1, 1, 1, 1, 1, 0, 0,
174 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000175/* case 0x001C: * FILE SEPARATOR */
176/* case 0x001D: * GROUP SEPARATOR */
177/* case 0x001E: * RECORD SEPARATOR */
178/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000179 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000180/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000181 1, 0, 0, 0, 0, 0, 0, 0,
182 0, 0, 0, 0, 0, 0, 0, 0,
183 0, 0, 0, 0, 0, 0, 0, 0,
184 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000185
Benjamin Peterson14339b62009-01-31 16:36:08 +0000186 0, 0, 0, 0, 0, 0, 0, 0,
187 0, 0, 0, 0, 0, 0, 0, 0,
188 0, 0, 0, 0, 0, 0, 0, 0,
189 0, 0, 0, 0, 0, 0, 0, 0,
190 0, 0, 0, 0, 0, 0, 0, 0,
191 0, 0, 0, 0, 0, 0, 0, 0,
192 0, 0, 0, 0, 0, 0, 0, 0,
193 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000194};
195
Victor Stinnerfe226c02011-10-03 03:52:20 +0200196static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
197
Alexander Belopolsky40018472011-02-26 01:02:56 +0000198static PyObject *
199unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000200 PyObject **errorHandler,const char *encoding, const char *reason,
201 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
202 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
203
Alexander Belopolsky40018472011-02-26 01:02:56 +0000204static void
205raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300206 const char *encoding,
207 const Py_UNICODE *unicode, Py_ssize_t size,
208 Py_ssize_t startpos, Py_ssize_t endpos,
209 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000210
Christian Heimes190d79e2008-01-30 11:58:22 +0000211/* Same for linebreaks */
212static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000215/* 0x000B, * LINE TABULATION */
216/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000217/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000218 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000219 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000220/* 0x001C, * FILE SEPARATOR */
221/* 0x001D, * GROUP SEPARATOR */
222/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000223 0, 0, 0, 0, 1, 1, 1, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300239/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
240 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000241Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000242PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000243{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000244#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000245 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000246#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000247 /* This is actually an illegal character, so it should
248 not be passed to unichr. */
249 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000250#endif
251}
252
Thomas Wouters477c8d52006-05-27 19:21:47 +0000253/* --- Bloom Filters ----------------------------------------------------- */
254
255/* stuff to implement simple "bloom filters" for Unicode characters.
256 to keep things simple, we use a single bitmask, using the least 5
257 bits from each unicode characters as the bit index. */
258
259/* the linebreak mask is set up by Unicode_Init below */
260
Antoine Pitrouf068f942010-01-13 14:19:12 +0000261#if LONG_BIT >= 128
262#define BLOOM_WIDTH 128
263#elif LONG_BIT >= 64
264#define BLOOM_WIDTH 64
265#elif LONG_BIT >= 32
266#define BLOOM_WIDTH 32
267#else
268#error "LONG_BIT is smaller than 32"
269#endif
270
Thomas Wouters477c8d52006-05-27 19:21:47 +0000271#define BLOOM_MASK unsigned long
272
273static BLOOM_MASK bloom_linebreak;
274
Antoine Pitrouf068f942010-01-13 14:19:12 +0000275#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
276#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000277
Benjamin Peterson29060642009-01-31 22:14:21 +0000278#define BLOOM_LINEBREAK(ch) \
279 ((ch) < 128U ? ascii_linebreak[(ch)] : \
280 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000281
Alexander Belopolsky40018472011-02-26 01:02:56 +0000282Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200283make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000284{
285 /* calculate simple bloom-style bitmask for a given unicode string */
286
Antoine Pitrouf068f942010-01-13 14:19:12 +0000287 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000288 Py_ssize_t i;
289
290 mask = 0;
291 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293
294 return mask;
295}
296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200297#define BLOOM_MEMBER(mask, chr, str) \
298 (BLOOM(mask, chr) \
299 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000300
Guido van Rossumd57fd912000-03-10 22:53:23 +0000301/* --- Unicode Object ----------------------------------------------------- */
302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200303static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200304fixup(PyUnicodeObject *self, Py_UCS4 (*fixfct)(PyUnicodeObject *s));
305
306Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
307 Py_ssize_t size, Py_UCS4 ch,
308 int direction)
309{
310 /* like wcschr, but doesn't stop at NULL characters */
311 Py_ssize_t i;
312 if (direction == 1) {
313 for(i = 0; i < size; i++)
314 if (PyUnicode_READ(kind, s, i) == ch)
315 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
316 }
317 else {
318 for(i = size-1; i >= 0; i--)
319 if (PyUnicode_READ(kind, s, i) == ch)
320 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
321 }
322 return NULL;
323}
324
Victor Stinnerfe226c02011-10-03 03:52:20 +0200325static PyObject*
326resize_compact(PyObject *unicode, Py_ssize_t length)
327{
328 Py_ssize_t char_size;
329 Py_ssize_t struct_size;
330 Py_ssize_t new_size;
331 int share_wstr;
332
333 assert(PyUnicode_IS_READY(unicode));
334 char_size = PyUnicode_CHARACTER_SIZE(unicode);
335 if (PyUnicode_IS_COMPACT_ASCII(unicode))
336 struct_size = sizeof(PyASCIIObject);
337 else
338 struct_size = sizeof(PyCompactUnicodeObject);
339 share_wstr = (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(unicode));
340
341 _Py_DEC_REFTOTAL;
342 _Py_ForgetReference(unicode);
343
344 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
345 PyErr_NoMemory();
346 return NULL;
347 }
348 new_size = (struct_size + (length + 1) * char_size);
349
350 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
351 if (unicode == NULL) {
352 PyObject_Del(unicode);
353 PyErr_NoMemory();
354 return NULL;
355 }
356 _Py_NewReference(unicode);
357 _PyUnicode_LENGTH(unicode) = length;
358 if (share_wstr)
359 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
360 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
361 length, 0);
362 return unicode;
363}
364
Alexander Belopolsky40018472011-02-26 01:02:56 +0000365static int
Victor Stinnerfe226c02011-10-03 03:52:20 +0200366resize_inplace(register PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000367{
368 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200370 assert(!PyUnicode_IS_COMPACT(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200371
Victor Stinnerfe226c02011-10-03 03:52:20 +0200372 assert(Py_REFCNT(unicode) == 1);
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200373 _PyUnicode_DIRTY(unicode);
Tim Petersced69f82003-09-16 20:30:58 +0000374
Victor Stinnerfe226c02011-10-03 03:52:20 +0200375 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
376 {
377 PyObject_DEL(_PyUnicode_UTF8(unicode));
378 _PyUnicode_UTF8(unicode) = NULL;
379 }
380
381 if (PyUnicode_IS_READY(unicode)) {
382 Py_ssize_t char_size;
383 Py_ssize_t new_size;
384 int share_wstr;
385 void *data;
386
387 data = _PyUnicode_DATA_ANY(unicode);
388 assert(data != NULL);
389 char_size = PyUnicode_CHARACTER_SIZE(unicode);
390 share_wstr = (_PyUnicode_WSTR(unicode) == data);
391
392 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
393 PyErr_NoMemory();
394 return -1;
395 }
396 new_size = (length + 1) * char_size;
397
398 data = (PyObject *)PyObject_REALLOC(data, new_size);
399 if (data == NULL) {
400 PyErr_NoMemory();
401 return -1;
402 }
403 _PyUnicode_DATA_ANY(unicode) = data;
404 if (share_wstr)
405 _PyUnicode_WSTR(unicode) = data;
406 _PyUnicode_LENGTH(unicode) = length;
407 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
408 if (share_wstr)
409 return 0;
410 }
411 if (_PyUnicode_WSTR(unicode) != NULL) {
412 assert(_PyUnicode_WSTR(unicode) != NULL);
413
414 oldstr = _PyUnicode_WSTR(unicode);
415 _PyUnicode_WSTR(unicode) = PyObject_REALLOC(_PyUnicode_WSTR(unicode),
416 sizeof(Py_UNICODE) * (length + 1));
417 if (!_PyUnicode_WSTR(unicode)) {
418 _PyUnicode_WSTR(unicode) = (Py_UNICODE *)oldstr;
419 PyErr_NoMemory();
420 return -1;
421 }
422 _PyUnicode_WSTR(unicode)[length] = 0;
423 _PyUnicode_WSTR_LENGTH(unicode) = length;
424 }
Guido van Rossumd57fd912000-03-10 22:53:23 +0000425 return 0;
426}
427
Victor Stinnerfe226c02011-10-03 03:52:20 +0200428static PyObject*
429resize_copy(PyObject *unicode, Py_ssize_t length)
430{
431 Py_ssize_t copy_length;
432 if (PyUnicode_IS_COMPACT(unicode)) {
433 PyObject *copy;
434 assert(PyUnicode_IS_READY(unicode));
435
436 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
437 if (copy == NULL)
438 return NULL;
439
440 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
441 if (PyUnicode_CopyCharacters(copy, 0,
442 unicode, 0,
443 copy_length) < 0)
444 {
445 Py_DECREF(copy);
446 return NULL;
447 }
448 return copy;
449 } else {
450 assert(_PyUnicode_WSTR(unicode) != NULL);
451 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
452 PyUnicodeObject *w = _PyUnicode_New(length);
453 if (w == NULL)
454 return NULL;
455 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
456 copy_length = Py_MIN(copy_length, length);
457 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
458 copy_length);
459 return (PyObject*)w;
460 }
461}
462
Guido van Rossumd57fd912000-03-10 22:53:23 +0000463/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000464 Ux0000 terminated; some code (e.g. new_identifier)
465 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000466
467 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000468 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000469
470*/
471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200472#ifdef Py_DEBUG
473int unicode_old_new_calls = 0;
474#endif
475
Alexander Belopolsky40018472011-02-26 01:02:56 +0000476static PyUnicodeObject *
477_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000478{
479 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200480 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000481
Thomas Wouters477c8d52006-05-27 19:21:47 +0000482 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000483 if (length == 0 && unicode_empty != NULL) {
484 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200485 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000486 }
487
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000488 /* Ensure we won't overflow the size. */
489 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
490 return (PyUnicodeObject *)PyErr_NoMemory();
491 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200492 if (length < 0) {
493 PyErr_SetString(PyExc_SystemError,
494 "Negative size passed to _PyUnicode_New");
495 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000496 }
497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200498#ifdef Py_DEBUG
499 ++unicode_old_new_calls;
500#endif
501
502 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
503 if (unicode == NULL)
504 return NULL;
505 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
506 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
507 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000508 PyErr_NoMemory();
509 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000510 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200511
Jeremy Hyltond8082792003-09-16 19:41:39 +0000512 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000513 * the caller fails before initializing str -- unicode_resize()
514 * reads str[0], and the Keep-Alive optimization can keep memory
515 * allocated for str alive across a call to unicode_dealloc(unicode).
516 * We don't want unicode_resize to read uninitialized memory in
517 * that case.
518 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200519 _PyUnicode_WSTR(unicode)[0] = 0;
520 _PyUnicode_WSTR(unicode)[length] = 0;
521 _PyUnicode_WSTR_LENGTH(unicode) = length;
522 _PyUnicode_HASH(unicode) = -1;
523 _PyUnicode_STATE(unicode).interned = 0;
524 _PyUnicode_STATE(unicode).kind = 0;
525 _PyUnicode_STATE(unicode).compact = 0;
526 _PyUnicode_STATE(unicode).ready = 0;
527 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200528 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200529 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200530 _PyUnicode_UTF8(unicode) = NULL;
531 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000532 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000533
Benjamin Peterson29060642009-01-31 22:14:21 +0000534 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000535 /* XXX UNREF/NEWREF interface should be more symmetrical */
536 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000537 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000538 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000539 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000540}
541
Victor Stinnerf42dc442011-10-02 23:33:16 +0200542static const char*
543unicode_kind_name(PyObject *unicode)
544{
545 assert(PyUnicode_Check(unicode));
546 if (!PyUnicode_IS_COMPACT(unicode))
547 {
548 if (!PyUnicode_IS_READY(unicode))
549 return "wstr";
550 switch(PyUnicode_KIND(unicode))
551 {
552 case PyUnicode_1BYTE_KIND:
553 if (PyUnicode_IS_COMPACT_ASCII(unicode))
554 return "legacy ascii";
555 else
556 return "legacy latin1";
557 case PyUnicode_2BYTE_KIND:
558 return "legacy UCS2";
559 case PyUnicode_4BYTE_KIND:
560 return "legacy UCS4";
561 default:
562 return "<legacy invalid kind>";
563 }
564 }
565 assert(PyUnicode_IS_READY(unicode));
566 switch(PyUnicode_KIND(unicode))
567 {
568 case PyUnicode_1BYTE_KIND:
569 if (PyUnicode_IS_COMPACT_ASCII(unicode))
570 return "ascii";
571 else
572 return "compact latin1";
573 case PyUnicode_2BYTE_KIND:
574 return "compact UCS2";
575 case PyUnicode_4BYTE_KIND:
576 return "compact UCS4";
577 default:
578 return "<invalid compact kind>";
579 }
580}
581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200582#ifdef Py_DEBUG
583int unicode_new_new_calls = 0;
584
585/* Functions wrapping macros for use in debugger */
586char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200587 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200588}
589
590void *_PyUnicode_compact_data(void *unicode) {
591 return _PyUnicode_COMPACT_DATA(unicode);
592}
593void *_PyUnicode_data(void *unicode){
594 printf("obj %p\n", unicode);
595 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
596 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
597 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
598 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
599 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
600 return PyUnicode_DATA(unicode);
601}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200602
603void
604_PyUnicode_Dump(PyObject *op)
605{
606 PyASCIIObject *ascii = (PyASCIIObject *)op;
607 printf("%s: len=%zu, wstr=%p",
608 unicode_kind_name(op),
609 ascii->length,
610 ascii->wstr);
611 if (!ascii->state.ascii) {
612 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
613 printf(" (%zu), utf8=%p (%zu)",
614 compact->wstr_length,
615 compact->utf8,
616 compact->utf8_length);
617 }
618 if (!ascii->state.compact) {
619 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
620 printf(", data=%p",
621 unicode->data.any);
622 }
623 printf("\n");
624}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200625#endif
626
627PyObject *
628PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
629{
630 PyObject *obj;
631 PyCompactUnicodeObject *unicode;
632 void *data;
633 int kind_state;
634 int is_sharing = 0, is_ascii = 0;
635 Py_ssize_t char_size;
636 Py_ssize_t struct_size;
637
638 /* Optimization for empty strings */
639 if (size == 0 && unicode_empty != NULL) {
640 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200641 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200642 }
643
644#ifdef Py_DEBUG
645 ++unicode_new_new_calls;
646#endif
647
648 struct_size = sizeof(PyCompactUnicodeObject);
649 if (maxchar < 128) {
650 kind_state = PyUnicode_1BYTE_KIND;
651 char_size = 1;
652 is_ascii = 1;
653 struct_size = sizeof(PyASCIIObject);
654 }
655 else if (maxchar < 256) {
656 kind_state = PyUnicode_1BYTE_KIND;
657 char_size = 1;
658 }
659 else if (maxchar < 65536) {
660 kind_state = PyUnicode_2BYTE_KIND;
661 char_size = 2;
662 if (sizeof(wchar_t) == 2)
663 is_sharing = 1;
664 }
665 else {
666 kind_state = PyUnicode_4BYTE_KIND;
667 char_size = 4;
668 if (sizeof(wchar_t) == 4)
669 is_sharing = 1;
670 }
671
672 /* Ensure we won't overflow the size. */
673 if (size < 0) {
674 PyErr_SetString(PyExc_SystemError,
675 "Negative size passed to PyUnicode_New");
676 return NULL;
677 }
678 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
679 return PyErr_NoMemory();
680
681 /* Duplicated allocation code from _PyObject_New() instead of a call to
682 * PyObject_New() so we are able to allocate space for the object and
683 * it's data buffer.
684 */
685 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
686 if (obj == NULL)
687 return PyErr_NoMemory();
688 obj = PyObject_INIT(obj, &PyUnicode_Type);
689 if (obj == NULL)
690 return NULL;
691
692 unicode = (PyCompactUnicodeObject *)obj;
693 if (is_ascii)
694 data = ((PyASCIIObject*)obj) + 1;
695 else
696 data = unicode + 1;
697 _PyUnicode_LENGTH(unicode) = size;
698 _PyUnicode_HASH(unicode) = -1;
699 _PyUnicode_STATE(unicode).interned = 0;
700 _PyUnicode_STATE(unicode).kind = kind_state;
701 _PyUnicode_STATE(unicode).compact = 1;
702 _PyUnicode_STATE(unicode).ready = 1;
703 _PyUnicode_STATE(unicode).ascii = is_ascii;
704 if (is_ascii) {
705 ((char*)data)[size] = 0;
706 _PyUnicode_WSTR(unicode) = NULL;
707 }
708 else if (kind_state == PyUnicode_1BYTE_KIND) {
709 ((char*)data)[size] = 0;
710 _PyUnicode_WSTR(unicode) = NULL;
711 _PyUnicode_WSTR_LENGTH(unicode) = 0;
712 unicode->utf8_length = 0;
713 unicode->utf8 = NULL;
714 }
715 else {
716 unicode->utf8 = NULL;
717 if (kind_state == PyUnicode_2BYTE_KIND)
718 ((Py_UCS2*)data)[size] = 0;
719 else /* kind_state == PyUnicode_4BYTE_KIND */
720 ((Py_UCS4*)data)[size] = 0;
721 if (is_sharing) {
722 _PyUnicode_WSTR_LENGTH(unicode) = size;
723 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
724 }
725 else {
726 _PyUnicode_WSTR_LENGTH(unicode) = 0;
727 _PyUnicode_WSTR(unicode) = NULL;
728 }
729 }
730 return obj;
731}
732
733#if SIZEOF_WCHAR_T == 2
734/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
735 will decode surrogate pairs, the other conversions are implemented as macros
736 for efficency.
737
738 This function assumes that unicode can hold one more code point than wstr
739 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200740static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
742 PyUnicodeObject *unicode)
743{
744 const wchar_t *iter;
745 Py_UCS4 *ucs4_out;
746
747 assert(unicode && PyUnicode_Check(unicode));
748 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
749 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
750
751 for (iter = begin; iter < end; ) {
752 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
753 _PyUnicode_GET_LENGTH(unicode)));
754 if (*iter >= 0xD800 && *iter <= 0xDBFF
755 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
756 {
757 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
758 iter += 2;
759 }
760 else {
761 *ucs4_out++ = *iter;
762 iter++;
763 }
764 }
765 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
766 _PyUnicode_GET_LENGTH(unicode)));
767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200768}
769#endif
770
Victor Stinnercd9950f2011-10-02 00:34:53 +0200771static int
772_PyUnicode_Dirty(PyObject *unicode)
773{
774 assert(PyUnicode_Check(unicode));
775 if (Py_REFCNT(unicode) != 1) {
776 PyErr_SetString(PyExc_ValueError,
777 "Cannot modify a string having more than 1 reference");
778 return -1;
779 }
780 _PyUnicode_DIRTY(unicode);
781 return 0;
782}
783
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200784Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200785PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
786 PyObject *from, Py_ssize_t from_start,
787 Py_ssize_t how_many)
788{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200789 unsigned int from_kind, to_kind;
790 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200791
Victor Stinnerb1536152011-09-30 02:26:10 +0200792 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
793 PyErr_BadInternalCall();
794 return -1;
795 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200796
797 if (PyUnicode_READY(from))
798 return -1;
799 if (PyUnicode_READY(to))
800 return -1;
801
Victor Stinnerff9e50f2011-09-28 22:17:19 +0200802 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200803 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
804 PyErr_Format(PyExc_ValueError,
805 "Cannot write %zi characters at %zi "
806 "in a string of %zi characters",
807 how_many, to_start, PyUnicode_GET_LENGTH(to));
808 return -1;
809 }
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200810 if (how_many == 0)
811 return 0;
812
Victor Stinnercd9950f2011-10-02 00:34:53 +0200813 if (_PyUnicode_Dirty(to))
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200814 return -1;
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200816 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200817 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200818 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200819 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820
Victor Stinnerf42dc442011-10-02 23:33:16 +0200821 if (from_kind == to_kind
822 /* deny latin1 => ascii */
823 && PyUnicode_MAX_CHAR_VALUE(to) >= PyUnicode_MAX_CHAR_VALUE(from))
824 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200825 Py_MEMCPY((char*)to_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200826 + PyUnicode_KIND_SIZE(to_kind, to_start),
Victor Stinnera0702ab2011-09-29 14:14:38 +0200827 (char*)from_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200828 + PyUnicode_KIND_SIZE(from_kind, from_start),
829 PyUnicode_KIND_SIZE(to_kind, how_many));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200830 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200831 else if (from_kind == PyUnicode_1BYTE_KIND
832 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200833 {
834 _PyUnicode_CONVERT_BYTES(
835 Py_UCS1, Py_UCS2,
836 PyUnicode_1BYTE_DATA(from) + from_start,
837 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
838 PyUnicode_2BYTE_DATA(to) + to_start
839 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200840 }
Victor Stinner157f83f2011-09-28 21:41:31 +0200841 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200842 && to_kind == PyUnicode_4BYTE_KIND)
843 {
844 _PyUnicode_CONVERT_BYTES(
845 Py_UCS1, Py_UCS4,
846 PyUnicode_1BYTE_DATA(from) + from_start,
847 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
848 PyUnicode_4BYTE_DATA(to) + to_start
849 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200850 }
851 else if (from_kind == PyUnicode_2BYTE_KIND
852 && to_kind == PyUnicode_4BYTE_KIND)
853 {
854 _PyUnicode_CONVERT_BYTES(
855 Py_UCS2, Py_UCS4,
856 PyUnicode_2BYTE_DATA(from) + from_start,
857 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
858 PyUnicode_4BYTE_DATA(to) + to_start
859 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200860 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200861 else {
862 int invalid_kinds;
Victor Stinnerf42dc442011-10-02 23:33:16 +0200863
864 /* check if max_char(from substring) <= max_char(to) */
865 if (from_kind > to_kind
866 /* latin1 => ascii */
867 || (PyUnicode_IS_COMPACT_ASCII(to)
868 && to_kind == PyUnicode_1BYTE_KIND
869 && !PyUnicode_IS_COMPACT_ASCII(from)))
870 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200871 /* slow path to check for character overflow */
872 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
873 Py_UCS4 ch, maxchar;
874 Py_ssize_t i;
875
876 maxchar = 0;
877 invalid_kinds = 0;
878 for (i=0; i < how_many; i++) {
879 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
880 if (ch > maxchar) {
881 maxchar = ch;
882 if (maxchar > to_maxchar) {
883 invalid_kinds = 1;
884 break;
885 }
886 }
887 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
888 }
889 }
890 else
891 invalid_kinds = 1;
892 if (invalid_kinds) {
893 PyErr_Format(PyExc_ValueError,
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 "Cannot copy %s characters "
895 "into a string of %s characters",
896 unicode_kind_name(from),
897 unicode_kind_name(to));
Victor Stinnera0702ab2011-09-29 14:14:38 +0200898 return -1;
899 }
900 }
901 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200902}
903
Victor Stinner17222162011-09-28 22:15:37 +0200904/* Find the maximum code point and count the number of surrogate pairs so a
905 correct string length can be computed before converting a string to UCS4.
906 This function counts single surrogates as a character and not as a pair.
907
908 Return 0 on success, or -1 on error. */
909static int
910find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
911 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912{
913 const wchar_t *iter;
914
Victor Stinnerc53be962011-10-02 21:33:54 +0200915 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200916 if (num_surrogates == NULL || maxchar == NULL) {
917 PyErr_SetString(PyExc_SystemError,
918 "unexpected NULL arguments to "
919 "PyUnicode_FindMaxCharAndNumSurrogatePairs");
920 return -1;
921 }
922
923 *num_surrogates = 0;
924 *maxchar = 0;
925
926 for (iter = begin; iter < end; ) {
927 if (*iter > *maxchar)
928 *maxchar = *iter;
929#if SIZEOF_WCHAR_T == 2
930 if (*iter >= 0xD800 && *iter <= 0xDBFF
931 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
932 {
933 Py_UCS4 surrogate_val;
934 surrogate_val = (((iter[0] & 0x3FF)<<10)
935 | (iter[1] & 0x3FF)) + 0x10000;
936 ++(*num_surrogates);
937 if (surrogate_val > *maxchar)
938 *maxchar = surrogate_val;
939 iter += 2;
940 }
941 else
942 iter++;
943#else
944 iter++;
945#endif
946 }
947 return 0;
948}
949
950#ifdef Py_DEBUG
951int unicode_ready_calls = 0;
952#endif
953
954int
Victor Stinnerd8f65102011-09-29 19:43:17 +0200955_PyUnicode_Ready(PyObject *obj)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956{
Victor Stinnerd8f65102011-09-29 19:43:17 +0200957 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 wchar_t *end;
959 Py_UCS4 maxchar = 0;
960 Py_ssize_t num_surrogates;
961#if SIZEOF_WCHAR_T == 2
962 Py_ssize_t length_wo_surrogates;
963#endif
964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200965 /* _PyUnicode_Ready() is only intented for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +0200966 strings were created using _PyObject_New() and where no canonical
967 representation (the str field) has been set yet aka strings
968 which are not yet ready. */
969 assert(PyUnicode_Check(obj));
970 assert(!PyUnicode_IS_READY(obj));
971 assert(!PyUnicode_IS_COMPACT(obj));
972 assert(_PyUnicode_KIND(obj) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200973 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +0200974 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200975 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +0200976 /* Actually, it should neither be interned nor be anything else: */
977 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978
979#ifdef Py_DEBUG
980 ++unicode_ready_calls;
981#endif
982
983 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +0200984 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +0200985 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200986 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987
988 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +0200989 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
990 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200991 PyErr_NoMemory();
992 return -1;
993 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200994 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 _PyUnicode_WSTR(unicode), end,
996 PyUnicode_1BYTE_DATA(unicode));
997 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
998 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
999 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1000 if (maxchar < 128) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001001 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001002 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001003 }
1004 else {
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001005 _PyUnicode_UTF8(unicode) = NULL;
1006 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001007 }
1008 PyObject_FREE(_PyUnicode_WSTR(unicode));
1009 _PyUnicode_WSTR(unicode) = NULL;
1010 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1011 }
1012 /* In this case we might have to convert down from 4-byte native
1013 wchar_t to 2-byte unicode. */
1014 else if (maxchar < 65536) {
1015 assert(num_surrogates == 0 &&
1016 "FindMaxCharAndNumSurrogatePairs() messed up");
1017
Victor Stinner506f5922011-09-28 22:34:18 +02001018#if SIZEOF_WCHAR_T == 2
1019 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001020 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001021 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1022 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1023 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001024 _PyUnicode_UTF8(unicode) = NULL;
1025 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001026#else
1027 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001028 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001029 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001030 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001031 PyErr_NoMemory();
1032 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033 }
Victor Stinner506f5922011-09-28 22:34:18 +02001034 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1035 _PyUnicode_WSTR(unicode), end,
1036 PyUnicode_2BYTE_DATA(unicode));
1037 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1038 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1039 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001040 _PyUnicode_UTF8(unicode) = NULL;
1041 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001042 PyObject_FREE(_PyUnicode_WSTR(unicode));
1043 _PyUnicode_WSTR(unicode) = NULL;
1044 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1045#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 }
1047 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1048 else {
1049#if SIZEOF_WCHAR_T == 2
1050 /* in case the native representation is 2-bytes, we need to allocate a
1051 new normalized 4-byte version. */
1052 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001053 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1054 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001055 PyErr_NoMemory();
1056 return -1;
1057 }
1058 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1059 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001060 _PyUnicode_UTF8(unicode) = NULL;
1061 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinnerc53be962011-10-02 21:33:54 +02001062 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001063 PyObject_FREE(_PyUnicode_WSTR(unicode));
1064 _PyUnicode_WSTR(unicode) = NULL;
1065 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1066#else
1067 assert(num_surrogates == 0);
1068
Victor Stinnerc3c74152011-10-02 20:39:55 +02001069 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001071 _PyUnicode_UTF8(unicode) = NULL;
1072 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1074#endif
1075 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1076 }
1077 _PyUnicode_STATE(unicode).ready = 1;
1078 return 0;
1079}
1080
Alexander Belopolsky40018472011-02-26 01:02:56 +00001081static void
1082unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001083{
Walter Dörwald16807132007-05-25 13:52:07 +00001084 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001085 case SSTATE_NOT_INTERNED:
1086 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001087
Benjamin Peterson29060642009-01-31 22:14:21 +00001088 case SSTATE_INTERNED_MORTAL:
1089 /* revive dead object temporarily for DelItem */
1090 Py_REFCNT(unicode) = 3;
1091 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1092 Py_FatalError(
1093 "deletion of interned string failed");
1094 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001095
Benjamin Peterson29060642009-01-31 22:14:21 +00001096 case SSTATE_INTERNED_IMMORTAL:
1097 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001098
Benjamin Peterson29060642009-01-31 22:14:21 +00001099 default:
1100 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001101 }
1102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001103 if (_PyUnicode_WSTR(unicode) &&
1104 (!PyUnicode_IS_READY(unicode) ||
1105 _PyUnicode_WSTR(unicode) != PyUnicode_DATA(unicode)))
1106 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001107 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001108 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109
1110 if (PyUnicode_IS_COMPACT(unicode)) {
1111 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001112 }
1113 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001114 if (_PyUnicode_DATA_ANY(unicode))
1115 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001116 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001117 }
1118}
1119
Alexander Belopolsky40018472011-02-26 01:02:56 +00001120static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001121unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001122{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001123 if (Py_REFCNT(unicode) != 1)
1124 return 0;
1125 if (PyUnicode_CHECK_INTERNED(unicode))
1126 return 0;
1127 if (unicode == unicode_empty)
1128 return 0;
1129 if (PyUnicode_WSTR_LENGTH(unicode) == 1) {
1130 Py_UCS4 ch;
1131 if (PyUnicode_IS_COMPACT(unicode))
1132 ch = PyUnicode_READ_CHAR(unicode, 0);
1133 else
1134 ch = _PyUnicode_WSTR(unicode)[0];
1135 if (ch < 256 && unicode_latin1[ch] == unicode)
1136 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001137 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001138 /* FIXME: reenable resize_inplace */
1139 if (!PyUnicode_IS_COMPACT(unicode))
1140 return 0;
1141 return 1;
1142}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001143
Victor Stinnerfe226c02011-10-03 03:52:20 +02001144static int
1145unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1146{
1147 PyObject *unicode;
1148 Py_ssize_t old_length;
1149
1150 assert(p_unicode != NULL);
1151 unicode = *p_unicode;
1152
1153 assert(unicode != NULL);
1154 assert(PyUnicode_Check(unicode));
1155 assert(0 <= length);
1156
1157 if (!PyUnicode_IS_COMPACT(unicode) && !PyUnicode_IS_READY(unicode))
1158 old_length = PyUnicode_WSTR_LENGTH(unicode);
1159 else
1160 old_length = PyUnicode_GET_LENGTH(unicode);
1161 if (old_length == length)
1162 return 0;
1163
1164 /* FIXME: really create a new object? */
1165 if (!unicode_resizable(unicode)) {
1166 PyObject *copy = resize_copy(unicode, length);
1167 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001168 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001169 Py_DECREF(*p_unicode);
1170 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001171 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001172 }
1173
Victor Stinnerfe226c02011-10-03 03:52:20 +02001174 if (PyUnicode_IS_COMPACT(unicode)) {
1175 *p_unicode = resize_compact(unicode, length);
1176 if (*p_unicode == NULL)
1177 return -1;
1178 return 0;
1179 } else
1180 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001181}
1182
Alexander Belopolsky40018472011-02-26 01:02:56 +00001183int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001184PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001185{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001186 PyObject *unicode;
1187 if (p_unicode == NULL) {
1188 PyErr_BadInternalCall();
1189 return -1;
1190 }
1191 unicode = *p_unicode;
1192 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1193 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1194 {
1195 PyErr_BadInternalCall();
1196 return -1;
1197 }
1198 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001199}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201static PyObject*
1202get_latin1_char(unsigned char ch)
1203{
Victor Stinnera464fc12011-10-02 20:39:30 +02001204 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001205 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001206 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207 if (!unicode)
1208 return NULL;
1209 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
1210 unicode_latin1[ch] = unicode;
1211 }
1212 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001213 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001214}
1215
Alexander Belopolsky40018472011-02-26 01:02:56 +00001216PyObject *
1217PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001218{
1219 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 Py_UCS4 maxchar = 0;
1221 Py_ssize_t num_surrogates;
1222
1223 if (u == NULL)
1224 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001225
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001226 /* If the Unicode data is known at construction time, we can apply
1227 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 /* Optimization for empty strings */
1230 if (size == 0 && unicode_empty != NULL) {
1231 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001232 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001233 }
Tim Petersced69f82003-09-16 20:30:58 +00001234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235 /* Single character Unicode objects in the Latin-1 range are
1236 shared when using this constructor */
1237 if (size == 1 && *u < 256)
1238 return get_latin1_char((unsigned char)*u);
1239
1240 /* If not empty and not single character, copy the Unicode data
1241 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001242 if (find_maxchar_surrogates(u, u + size,
1243 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001244 return NULL;
1245
1246 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1247 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001248 if (!unicode)
1249 return NULL;
1250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 switch (PyUnicode_KIND(unicode)) {
1252 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001253 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1255 break;
1256 case PyUnicode_2BYTE_KIND:
1257#if Py_UNICODE_SIZE == 2
1258 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1259#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001260 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001261 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1262#endif
1263 break;
1264 case PyUnicode_4BYTE_KIND:
1265#if SIZEOF_WCHAR_T == 2
1266 /* This is the only case which has to process surrogates, thus
1267 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001268 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001269#else
1270 assert(num_surrogates == 0);
1271 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1272#endif
1273 break;
1274 default:
1275 assert(0 && "Impossible state");
1276 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001277
1278 return (PyObject *)unicode;
1279}
1280
Alexander Belopolsky40018472011-02-26 01:02:56 +00001281PyObject *
1282PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001283{
1284 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001285
Benjamin Peterson14339b62009-01-31 16:36:08 +00001286 if (size < 0) {
1287 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001288 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001289 return NULL;
1290 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001291
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001292 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001293 some optimizations which share commonly used objects.
1294 Also, this means the input must be UTF-8, so fall back to the
1295 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001296 if (u != NULL) {
1297
Benjamin Peterson29060642009-01-31 22:14:21 +00001298 /* Optimization for empty strings */
1299 if (size == 0 && unicode_empty != NULL) {
1300 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001301 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001302 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001303
1304 /* Single characters are shared when using this constructor.
1305 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306 if (size == 1 && Py_CHARMASK(*u) < 128)
1307 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001308
1309 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001310 }
1311
Walter Dörwald55507312007-05-18 13:12:10 +00001312 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001313 if (!unicode)
1314 return NULL;
1315
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001316 return (PyObject *)unicode;
1317}
1318
Alexander Belopolsky40018472011-02-26 01:02:56 +00001319PyObject *
1320PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001321{
1322 size_t size = strlen(u);
1323 if (size > PY_SSIZE_T_MAX) {
1324 PyErr_SetString(PyExc_OverflowError, "input too long");
1325 return NULL;
1326 }
1327
1328 return PyUnicode_FromStringAndSize(u, size);
1329}
1330
Victor Stinnere57b1c02011-09-28 22:20:48 +02001331static PyObject*
1332_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334 PyObject *res;
1335 unsigned char max = 127;
1336 Py_ssize_t i;
1337 for (i = 0; i < size; i++) {
1338 if (u[i] & 0x80) {
1339 max = 255;
1340 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001341 }
1342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 res = PyUnicode_New(size, max);
1344 if (!res)
1345 return NULL;
1346 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
1347 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001348}
1349
Victor Stinnere57b1c02011-09-28 22:20:48 +02001350static PyObject*
1351_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352{
1353 PyObject *res;
1354 Py_UCS2 max = 0;
1355 Py_ssize_t i;
1356 for (i = 0; i < size; i++)
1357 if (u[i] > max)
1358 max = u[i];
1359 res = PyUnicode_New(size, max);
1360 if (!res)
1361 return NULL;
1362 if (max >= 256)
1363 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1364 else
1365 for (i = 0; i < size; i++)
1366 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
1367 return res;
1368}
1369
Victor Stinnere57b1c02011-09-28 22:20:48 +02001370static PyObject*
1371_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372{
1373 PyObject *res;
1374 Py_UCS4 max = 0;
1375 Py_ssize_t i;
1376 for (i = 0; i < size; i++)
1377 if (u[i] > max)
1378 max = u[i];
1379 res = PyUnicode_New(size, max);
1380 if (!res)
1381 return NULL;
1382 if (max >= 0x10000)
1383 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1384 else {
1385 int kind = PyUnicode_KIND(res);
1386 void *data = PyUnicode_DATA(res);
1387 for (i = 0; i < size; i++)
1388 PyUnicode_WRITE(kind, data, i, u[i]);
1389 }
1390 return res;
1391}
1392
1393PyObject*
1394PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1395{
1396 switch(kind) {
1397 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001398 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001400 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001402 return _PyUnicode_FromUCS4(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 }
Victor Stinner202b62b2011-10-01 23:48:37 +02001404 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001405 return NULL;
1406}
1407
Victor Stinner034f6cf2011-09-30 02:26:44 +02001408PyObject*
1409PyUnicode_Copy(PyObject *unicode)
1410{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001411 Py_ssize_t size;
1412 PyObject *copy;
1413 void *data;
1414
Victor Stinner034f6cf2011-09-30 02:26:44 +02001415 if (!PyUnicode_Check(unicode)) {
1416 PyErr_BadInternalCall();
1417 return NULL;
1418 }
1419 if (PyUnicode_READY(unicode))
1420 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001421
1422 size = PyUnicode_GET_LENGTH(unicode);
1423 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1424 if (!copy)
1425 return NULL;
1426 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1427
1428 data = PyUnicode_DATA(unicode);
1429 switch (PyUnicode_KIND(unicode))
1430 {
1431 case PyUnicode_1BYTE_KIND:
1432 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1433 break;
1434 case PyUnicode_2BYTE_KIND:
1435 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1436 break;
1437 case PyUnicode_4BYTE_KIND:
1438 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1439 break;
1440 default:
1441 assert(0);
1442 break;
1443 }
1444 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001445}
1446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447
Victor Stinnerbc603d12011-10-02 01:00:40 +02001448/* Widen Unicode objects to larger buffers. Don't write terminating null
1449 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450
1451void*
1452_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1453{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001454 Py_ssize_t len;
1455 void *result;
1456 unsigned int skind;
1457
1458 if (PyUnicode_READY(s))
1459 return NULL;
1460
1461 len = PyUnicode_GET_LENGTH(s);
1462 skind = PyUnicode_KIND(s);
1463 if (skind >= kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464 PyErr_SetString(PyExc_RuntimeError, "invalid widening attempt");
1465 return NULL;
1466 }
1467 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001468 case PyUnicode_2BYTE_KIND:
1469 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1470 if (!result)
1471 return PyErr_NoMemory();
1472 assert(skind == PyUnicode_1BYTE_KIND);
1473 _PyUnicode_CONVERT_BYTES(
1474 Py_UCS1, Py_UCS2,
1475 PyUnicode_1BYTE_DATA(s),
1476 PyUnicode_1BYTE_DATA(s) + len,
1477 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001479 case PyUnicode_4BYTE_KIND:
1480 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1481 if (!result)
1482 return PyErr_NoMemory();
1483 if (skind == PyUnicode_2BYTE_KIND) {
1484 _PyUnicode_CONVERT_BYTES(
1485 Py_UCS2, Py_UCS4,
1486 PyUnicode_2BYTE_DATA(s),
1487 PyUnicode_2BYTE_DATA(s) + len,
1488 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001489 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001490 else {
1491 assert(skind == PyUnicode_1BYTE_KIND);
1492 _PyUnicode_CONVERT_BYTES(
1493 Py_UCS1, Py_UCS4,
1494 PyUnicode_1BYTE_DATA(s),
1495 PyUnicode_1BYTE_DATA(s) + len,
1496 result);
1497 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001498 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001499 default:
1500 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001501 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001502 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001503 return NULL;
1504}
1505
1506static Py_UCS4*
1507as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1508 int copy_null)
1509{
1510 int kind;
1511 void *data;
1512 Py_ssize_t len, targetlen;
1513 if (PyUnicode_READY(string) == -1)
1514 return NULL;
1515 kind = PyUnicode_KIND(string);
1516 data = PyUnicode_DATA(string);
1517 len = PyUnicode_GET_LENGTH(string);
1518 targetlen = len;
1519 if (copy_null)
1520 targetlen++;
1521 if (!target) {
1522 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1523 PyErr_NoMemory();
1524 return NULL;
1525 }
1526 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1527 if (!target) {
1528 PyErr_NoMemory();
1529 return NULL;
1530 }
1531 }
1532 else {
1533 if (targetsize < targetlen) {
1534 PyErr_Format(PyExc_SystemError,
1535 "string is longer than the buffer");
1536 if (copy_null && 0 < targetsize)
1537 target[0] = 0;
1538 return NULL;
1539 }
1540 }
1541 if (kind != PyUnicode_4BYTE_KIND) {
1542 Py_ssize_t i;
1543 for (i = 0; i < len; i++)
1544 target[i] = PyUnicode_READ(kind, data, i);
1545 }
1546 else
1547 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1548 if (copy_null)
1549 target[len] = 0;
1550 return target;
1551}
1552
1553Py_UCS4*
1554PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1555 int copy_null)
1556{
1557 if (target == NULL || targetsize < 1) {
1558 PyErr_BadInternalCall();
1559 return NULL;
1560 }
1561 return as_ucs4(string, target, targetsize, copy_null);
1562}
1563
1564Py_UCS4*
1565PyUnicode_AsUCS4Copy(PyObject *string)
1566{
1567 return as_ucs4(string, NULL, 0, 1);
1568}
1569
1570#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001571
Alexander Belopolsky40018472011-02-26 01:02:56 +00001572PyObject *
1573PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001574{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001575 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001576 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001577 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001578 PyErr_BadInternalCall();
1579 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001580 }
1581
Martin v. Löwis790465f2008-04-05 20:41:37 +00001582 if (size == -1) {
1583 size = wcslen(w);
1584 }
1585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001586 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001587}
1588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001590
Walter Dörwald346737f2007-05-31 10:44:43 +00001591static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001592makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1593 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001594{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001595 *fmt++ = '%';
1596 if (width) {
1597 if (zeropad)
1598 *fmt++ = '0';
1599 fmt += sprintf(fmt, "%d", width);
1600 }
1601 if (precision)
1602 fmt += sprintf(fmt, ".%d", precision);
1603 if (longflag)
1604 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001605 else if (longlongflag) {
1606 /* longlongflag should only ever be nonzero on machines with
1607 HAVE_LONG_LONG defined */
1608#ifdef HAVE_LONG_LONG
1609 char *f = PY_FORMAT_LONG_LONG;
1610 while (*f)
1611 *fmt++ = *f++;
1612#else
1613 /* we shouldn't ever get here */
1614 assert(0);
1615 *fmt++ = 'l';
1616#endif
1617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001618 else if (size_tflag) {
1619 char *f = PY_FORMAT_SIZE_T;
1620 while (*f)
1621 *fmt++ = *f++;
1622 }
1623 *fmt++ = c;
1624 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00001625}
1626
Victor Stinner96865452011-03-01 23:44:09 +00001627/* helper for PyUnicode_FromFormatV() */
1628
1629static const char*
1630parse_format_flags(const char *f,
1631 int *p_width, int *p_precision,
1632 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
1633{
1634 int width, precision, longflag, longlongflag, size_tflag;
1635
1636 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
1637 f++;
1638 width = 0;
1639 while (Py_ISDIGIT((unsigned)*f))
1640 width = (width*10) + *f++ - '0';
1641 precision = 0;
1642 if (*f == '.') {
1643 f++;
1644 while (Py_ISDIGIT((unsigned)*f))
1645 precision = (precision*10) + *f++ - '0';
1646 if (*f == '%') {
1647 /* "%.3%s" => f points to "3" */
1648 f--;
1649 }
1650 }
1651 if (*f == '\0') {
1652 /* bogus format "%.1" => go backward, f points to "1" */
1653 f--;
1654 }
1655 if (p_width != NULL)
1656 *p_width = width;
1657 if (p_precision != NULL)
1658 *p_precision = precision;
1659
1660 /* Handle %ld, %lu, %lld and %llu. */
1661 longflag = 0;
1662 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00001663 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00001664
1665 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00001666 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00001667 longflag = 1;
1668 ++f;
1669 }
1670#ifdef HAVE_LONG_LONG
1671 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00001672 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001673 longlongflag = 1;
1674 f += 2;
1675 }
1676#endif
1677 }
1678 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00001679 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001680 size_tflag = 1;
1681 ++f;
1682 }
1683 if (p_longflag != NULL)
1684 *p_longflag = longflag;
1685 if (p_longlongflag != NULL)
1686 *p_longlongflag = longlongflag;
1687 if (p_size_tflag != NULL)
1688 *p_size_tflag = size_tflag;
1689 return f;
1690}
1691
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001692/* maximum number of characters required for output of %ld. 21 characters
1693 allows for 64-bit integers (in decimal) and an optional sign. */
1694#define MAX_LONG_CHARS 21
1695/* maximum number of characters required for output of %lld.
1696 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
1697 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
1698#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
1699
Walter Dörwaldd2034312007-05-18 16:29:38 +00001700PyObject *
1701PyUnicode_FromFormatV(const char *format, va_list vargs)
1702{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001703 va_list count;
1704 Py_ssize_t callcount = 0;
1705 PyObject **callresults = NULL;
1706 PyObject **callresult = NULL;
1707 Py_ssize_t n = 0;
1708 int width = 0;
1709 int precision = 0;
1710 int zeropad;
1711 const char* f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001712 PyUnicodeObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001713 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001714 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 Py_UCS4 maxchar = 127; /* result is ASCII by default */
1716 Py_UCS4 argmaxchar;
1717 Py_ssize_t numbersize = 0;
1718 char *numberresults = NULL;
1719 char *numberresult = NULL;
1720 Py_ssize_t i;
1721 int kind;
1722 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001723
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001724 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001725 /* step 1: count the number of %S/%R/%A/%s format specifications
1726 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
1727 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728 * result in an array)
1729 * also esimate a upper bound for all the number formats in the string,
1730 * numbers will be formated in step 3 and be keept in a '\0'-separated
1731 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00001732 for (f = format; *f; f++) {
1733 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001734 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001735 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
1736 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
1737 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
1738 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001741#ifdef HAVE_LONG_LONG
1742 if (longlongflag) {
1743 if (width < MAX_LONG_LONG_CHARS)
1744 width = MAX_LONG_LONG_CHARS;
1745 }
1746 else
1747#endif
1748 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
1749 including sign. Decimal takes the most space. This
1750 isn't enough for octal. If a width is specified we
1751 need more (which we allocate later). */
1752 if (width < MAX_LONG_CHARS)
1753 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754
1755 /* account for the size + '\0' to separate numbers
1756 inside of the numberresults buffer */
1757 numbersize += (width + 1);
1758 }
1759 }
1760 else if ((unsigned char)*f > 127) {
1761 PyErr_Format(PyExc_ValueError,
1762 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
1763 "string, got a non-ASCII byte: 0x%02x",
1764 (unsigned char)*f);
1765 return NULL;
1766 }
1767 }
1768 /* step 2: allocate memory for the results of
1769 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
1770 if (callcount) {
1771 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
1772 if (!callresults) {
1773 PyErr_NoMemory();
1774 return NULL;
1775 }
1776 callresult = callresults;
1777 }
1778 /* step 2.5: allocate memory for the results of formating numbers */
1779 if (numbersize) {
1780 numberresults = PyObject_Malloc(numbersize);
1781 if (!numberresults) {
1782 PyErr_NoMemory();
1783 goto fail;
1784 }
1785 numberresult = numberresults;
1786 }
1787
1788 /* step 3: format numbers and figure out how large a buffer we need */
1789 for (f = format; *f; f++) {
1790 if (*f == '%') {
1791 const char* p;
1792 int longflag;
1793 int longlongflag;
1794 int size_tflag;
1795 int numprinted;
1796
1797 p = f;
1798 zeropad = (f[1] == '0');
1799 f = parse_format_flags(f, &width, &precision,
1800 &longflag, &longlongflag, &size_tflag);
1801 switch (*f) {
1802 case 'c':
1803 {
1804 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001805 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 n++;
1807 break;
1808 }
1809 case '%':
1810 n++;
1811 break;
1812 case 'i':
1813 case 'd':
1814 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1815 width, precision, *f);
1816 if (longflag)
1817 numprinted = sprintf(numberresult, fmt,
1818 va_arg(count, long));
1819#ifdef HAVE_LONG_LONG
1820 else if (longlongflag)
1821 numprinted = sprintf(numberresult, fmt,
1822 va_arg(count, PY_LONG_LONG));
1823#endif
1824 else if (size_tflag)
1825 numprinted = sprintf(numberresult, fmt,
1826 va_arg(count, Py_ssize_t));
1827 else
1828 numprinted = sprintf(numberresult, fmt,
1829 va_arg(count, int));
1830 n += numprinted;
1831 /* advance by +1 to skip over the '\0' */
1832 numberresult += (numprinted + 1);
1833 assert(*(numberresult - 1) == '\0');
1834 assert(*(numberresult - 2) != '\0');
1835 assert(numprinted >= 0);
1836 assert(numberresult <= numberresults + numbersize);
1837 break;
1838 case 'u':
1839 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1840 width, precision, 'u');
1841 if (longflag)
1842 numprinted = sprintf(numberresult, fmt,
1843 va_arg(count, unsigned long));
1844#ifdef HAVE_LONG_LONG
1845 else if (longlongflag)
1846 numprinted = sprintf(numberresult, fmt,
1847 va_arg(count, unsigned PY_LONG_LONG));
1848#endif
1849 else if (size_tflag)
1850 numprinted = sprintf(numberresult, fmt,
1851 va_arg(count, size_t));
1852 else
1853 numprinted = sprintf(numberresult, fmt,
1854 va_arg(count, unsigned int));
1855 n += numprinted;
1856 numberresult += (numprinted + 1);
1857 assert(*(numberresult - 1) == '\0');
1858 assert(*(numberresult - 2) != '\0');
1859 assert(numprinted >= 0);
1860 assert(numberresult <= numberresults + numbersize);
1861 break;
1862 case 'x':
1863 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
1864 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
1865 n += numprinted;
1866 numberresult += (numprinted + 1);
1867 assert(*(numberresult - 1) == '\0');
1868 assert(*(numberresult - 2) != '\0');
1869 assert(numprinted >= 0);
1870 assert(numberresult <= numberresults + numbersize);
1871 break;
1872 case 'p':
1873 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
1874 /* %p is ill-defined: ensure leading 0x. */
1875 if (numberresult[1] == 'X')
1876 numberresult[1] = 'x';
1877 else if (numberresult[1] != 'x') {
1878 memmove(numberresult + 2, numberresult,
1879 strlen(numberresult) + 1);
1880 numberresult[0] = '0';
1881 numberresult[1] = 'x';
1882 numprinted += 2;
1883 }
1884 n += numprinted;
1885 numberresult += (numprinted + 1);
1886 assert(*(numberresult - 1) == '\0');
1887 assert(*(numberresult - 2) != '\0');
1888 assert(numprinted >= 0);
1889 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001890 break;
1891 case 's':
1892 {
1893 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00001894 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001895 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
1896 if (!str)
1897 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 /* since PyUnicode_DecodeUTF8 returns already flexible
1899 unicode objects, there is no need to call ready on them */
1900 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001901 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001902 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001903 /* Remember the str and switch to the next slot */
1904 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001905 break;
1906 }
1907 case 'U':
1908 {
1909 PyObject *obj = va_arg(count, PyObject *);
1910 assert(obj && PyUnicode_Check(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911 if (PyUnicode_READY(obj) == -1)
1912 goto fail;
1913 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001914 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001916 break;
1917 }
1918 case 'V':
1919 {
1920 PyObject *obj = va_arg(count, PyObject *);
1921 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001922 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001923 assert(obj || str);
1924 assert(!obj || PyUnicode_Check(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00001925 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 if (PyUnicode_READY(obj) == -1)
1927 goto fail;
1928 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001929 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001931 *callresult++ = NULL;
1932 }
1933 else {
1934 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
1935 if (!str_obj)
1936 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001937 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001938 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001939 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00001940 *callresult++ = str_obj;
1941 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001942 break;
1943 }
1944 case 'S':
1945 {
1946 PyObject *obj = va_arg(count, PyObject *);
1947 PyObject *str;
1948 assert(obj);
1949 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001951 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001953 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001955 /* Remember the str and switch to the next slot */
1956 *callresult++ = str;
1957 break;
1958 }
1959 case 'R':
1960 {
1961 PyObject *obj = va_arg(count, PyObject *);
1962 PyObject *repr;
1963 assert(obj);
1964 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001965 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001966 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001968 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001969 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001970 /* Remember the repr and switch to the next slot */
1971 *callresult++ = repr;
1972 break;
1973 }
1974 case 'A':
1975 {
1976 PyObject *obj = va_arg(count, PyObject *);
1977 PyObject *ascii;
1978 assert(obj);
1979 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001980 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00001981 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001982 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001983 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00001985 /* Remember the repr and switch to the next slot */
1986 *callresult++ = ascii;
1987 break;
1988 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001989 default:
1990 /* if we stumble upon an unknown
1991 formatting code, copy the rest of
1992 the format string to the output
1993 string. (we cannot just skip the
1994 code, since there's no way to know
1995 what's in the argument list) */
1996 n += strlen(p);
1997 goto expand;
1998 }
1999 } else
2000 n++;
2001 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002002 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002003 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002005 we don't have to resize the string.
2006 There can be no errors beyond this point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 string = (PyUnicodeObject *)PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002008 if (!string)
2009 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 kind = PyUnicode_KIND(string);
2011 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002012 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002016 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002017 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002018
2019 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002020 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2021 /* checking for == because the last argument could be a empty
2022 string, which causes i to point to end, the assert at the end of
2023 the loop */
2024 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002025
Benjamin Peterson14339b62009-01-31 16:36:08 +00002026 switch (*f) {
2027 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002028 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 const int ordinal = va_arg(vargs, int);
2030 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002031 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002032 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002033 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002034 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002035 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002036 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 case 'p':
2038 /* unused, since we already have the result */
2039 if (*f == 'p')
2040 (void) va_arg(vargs, void *);
2041 else
2042 (void) va_arg(vargs, int);
2043 /* extract the result from numberresults and append. */
2044 for (; *numberresult; ++i, ++numberresult)
2045 PyUnicode_WRITE(kind, data, i, *numberresult);
2046 /* skip over the separating '\0' */
2047 assert(*numberresult == '\0');
2048 numberresult++;
2049 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002050 break;
2051 case 's':
2052 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002053 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002054 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002055 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 size = PyUnicode_GET_LENGTH(*callresult);
2057 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002058 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2059 *callresult, 0,
2060 size) < 0)
2061 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002062 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002063 /* We're done with the unicode()/repr() => forget it */
2064 Py_DECREF(*callresult);
2065 /* switch to next unicode()/repr() result */
2066 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002067 break;
2068 }
2069 case 'U':
2070 {
2071 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002072 Py_ssize_t size;
2073 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2074 size = PyUnicode_GET_LENGTH(obj);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002075 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2076 obj, 0,
2077 size) < 0)
2078 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002080 break;
2081 }
2082 case 'V':
2083 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002084 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002085 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002086 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002087 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 size = PyUnicode_GET_LENGTH(obj);
2089 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002090 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2091 obj, 0,
2092 size) < 0)
2093 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002094 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002095 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002096 size = PyUnicode_GET_LENGTH(*callresult);
2097 assert(PyUnicode_KIND(*callresult) <=
2098 PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002099 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2100 *callresult,
2101 0, size) < 0)
2102 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002103 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002104 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002105 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002106 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002107 break;
2108 }
2109 case 'S':
2110 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002111 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002112 {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002113 /* unused, since we already have the result */
2114 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002115 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002116 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2117 *callresult, 0,
2118 PyUnicode_GET_LENGTH(*callresult)) < 0)
2119 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002120 i += PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002121 /* We're done with the unicode()/repr() => forget it */
2122 Py_DECREF(*callresult);
2123 /* switch to next unicode()/repr() result */
2124 ++callresult;
2125 break;
2126 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002127 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002128 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002129 break;
2130 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 for (; *p; ++p, ++i)
2132 PyUnicode_WRITE(kind, data, i, *p);
2133 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002134 goto end;
2135 }
Victor Stinner1205f272010-09-11 00:54:47 +00002136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002137 else {
2138 assert(i < PyUnicode_GET_LENGTH(string));
2139 PyUnicode_WRITE(kind, data, i++, *f);
2140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002141 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002142 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002143
Benjamin Peterson29060642009-01-31 22:14:21 +00002144 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002145 if (callresults)
2146 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002147 if (numberresults)
2148 PyObject_Free(numberresults);
2149 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002150 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002151 if (callresults) {
2152 PyObject **callresult2 = callresults;
2153 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002154 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002155 ++callresult2;
2156 }
2157 PyObject_Free(callresults);
2158 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002159 if (numberresults)
2160 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002161 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002162}
2163
Walter Dörwaldd2034312007-05-18 16:29:38 +00002164PyObject *
2165PyUnicode_FromFormat(const char *format, ...)
2166{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002167 PyObject* ret;
2168 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002169
2170#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002171 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002172#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002173 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002174#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002175 ret = PyUnicode_FromFormatV(format, vargs);
2176 va_end(vargs);
2177 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002178}
2179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180#ifdef HAVE_WCHAR_H
2181
Victor Stinner5593d8a2010-10-02 11:11:27 +00002182/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2183 convert a Unicode object to a wide character string.
2184
Victor Stinnerd88d9832011-09-06 02:00:05 +02002185 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002186 character) required to convert the unicode object. Ignore size argument.
2187
Victor Stinnerd88d9832011-09-06 02:00:05 +02002188 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002189 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002190 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002191static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002192unicode_aswidechar(PyUnicodeObject *unicode,
2193 wchar_t *w,
2194 Py_ssize_t size)
2195{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002196 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 const wchar_t *wstr;
2198
2199 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2200 if (wstr == NULL)
2201 return -1;
2202
Victor Stinner5593d8a2010-10-02 11:11:27 +00002203 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002204 if (size > res)
2205 size = res + 1;
2206 else
2207 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002209 return res;
2210 }
2211 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002213}
2214
2215Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002216PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002217 wchar_t *w,
2218 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002219{
2220 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002221 PyErr_BadInternalCall();
2222 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002223 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002224 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002225}
2226
Victor Stinner137c34c2010-09-29 10:25:54 +00002227wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002228PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002229 Py_ssize_t *size)
2230{
2231 wchar_t* buffer;
2232 Py_ssize_t buflen;
2233
2234 if (unicode == NULL) {
2235 PyErr_BadInternalCall();
2236 return NULL;
2237 }
2238
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002239 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 if (buflen == -1)
2241 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002242 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246
Victor Stinner137c34c2010-09-29 10:25:54 +00002247 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2248 if (buffer == NULL) {
2249 PyErr_NoMemory();
2250 return NULL;
2251 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002252 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002253 if (buflen == -1)
2254 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002255 if (size != NULL)
2256 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002257 return buffer;
2258}
2259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002261
Alexander Belopolsky40018472011-02-26 01:02:56 +00002262PyObject *
2263PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002266 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002267 PyErr_SetString(PyExc_ValueError,
2268 "chr() arg not in range(0x110000)");
2269 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002270 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 if (ordinal < 256)
2273 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 v = PyUnicode_New(1, ordinal);
2276 if (v == NULL)
2277 return NULL;
2278 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
2279 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002280}
2281
Alexander Belopolsky40018472011-02-26 01:02:56 +00002282PyObject *
2283PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002284{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002285 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002286 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002287 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002288 if (PyUnicode_READY(obj))
2289 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002290 Py_INCREF(obj);
2291 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002292 }
2293 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002294 /* For a Unicode subtype that's not a Unicode object,
2295 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002296 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002297 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002298 PyErr_Format(PyExc_TypeError,
2299 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002300 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002301 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002302}
2303
Alexander Belopolsky40018472011-02-26 01:02:56 +00002304PyObject *
2305PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002306 const char *encoding,
2307 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002308{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002309 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002310 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002311
Guido van Rossumd57fd912000-03-10 22:53:23 +00002312 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002313 PyErr_BadInternalCall();
2314 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002315 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002316
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002317 /* Decoding bytes objects is the most common case and should be fast */
2318 if (PyBytes_Check(obj)) {
2319 if (PyBytes_GET_SIZE(obj) == 0) {
2320 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002321 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002322 }
2323 else {
2324 v = PyUnicode_Decode(
2325 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2326 encoding, errors);
2327 }
2328 return v;
2329 }
2330
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002331 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002332 PyErr_SetString(PyExc_TypeError,
2333 "decoding str is not supported");
2334 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002335 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002336
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002337 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2338 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2339 PyErr_Format(PyExc_TypeError,
2340 "coercing to str: need bytes, bytearray "
2341 "or buffer-like object, %.80s found",
2342 Py_TYPE(obj)->tp_name);
2343 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002344 }
Tim Petersced69f82003-09-16 20:30:58 +00002345
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002346 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002347 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002348 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002349 }
Tim Petersced69f82003-09-16 20:30:58 +00002350 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002351 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002352
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002353 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002354 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002355}
2356
Victor Stinner600d3be2010-06-10 12:00:55 +00002357/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002358 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2359 1 on success. */
2360static int
2361normalize_encoding(const char *encoding,
2362 char *lower,
2363 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002364{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002365 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002366 char *l;
2367 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002368
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002369 e = encoding;
2370 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002371 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002372 while (*e) {
2373 if (l == l_end)
2374 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002375 if (Py_ISUPPER(*e)) {
2376 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002377 }
2378 else if (*e == '_') {
2379 *l++ = '-';
2380 e++;
2381 }
2382 else {
2383 *l++ = *e++;
2384 }
2385 }
2386 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002387 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002388}
2389
Alexander Belopolsky40018472011-02-26 01:02:56 +00002390PyObject *
2391PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002392 Py_ssize_t size,
2393 const char *encoding,
2394 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002395{
2396 PyObject *buffer = NULL, *unicode;
2397 Py_buffer info;
2398 char lower[11]; /* Enough for any encoding shortcut */
2399
2400 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002401 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002402
2403 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002404 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002405 if ((strcmp(lower, "utf-8") == 0) ||
2406 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002407 return PyUnicode_DecodeUTF8(s, size, errors);
2408 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002409 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002410 (strcmp(lower, "iso-8859-1") == 0))
2411 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002412#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002413 else if (strcmp(lower, "mbcs") == 0)
2414 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002415#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002416 else if (strcmp(lower, "ascii") == 0)
2417 return PyUnicode_DecodeASCII(s, size, errors);
2418 else if (strcmp(lower, "utf-16") == 0)
2419 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2420 else if (strcmp(lower, "utf-32") == 0)
2421 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2422 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002423
2424 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002425 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002426 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002427 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002428 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002429 if (buffer == NULL)
2430 goto onError;
2431 unicode = PyCodec_Decode(buffer, encoding, errors);
2432 if (unicode == NULL)
2433 goto onError;
2434 if (!PyUnicode_Check(unicode)) {
2435 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002436 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002437 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002438 Py_DECREF(unicode);
2439 goto onError;
2440 }
2441 Py_DECREF(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 if (PyUnicode_READY(unicode)) {
2443 Py_DECREF(unicode);
2444 return NULL;
2445 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002446 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002447
Benjamin Peterson29060642009-01-31 22:14:21 +00002448 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002449 Py_XDECREF(buffer);
2450 return NULL;
2451}
2452
Alexander Belopolsky40018472011-02-26 01:02:56 +00002453PyObject *
2454PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002455 const char *encoding,
2456 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002457{
2458 PyObject *v;
2459
2460 if (!PyUnicode_Check(unicode)) {
2461 PyErr_BadArgument();
2462 goto onError;
2463 }
2464
2465 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002466 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002467
2468 /* Decode via the codec registry */
2469 v = PyCodec_Decode(unicode, encoding, errors);
2470 if (v == NULL)
2471 goto onError;
2472 return v;
2473
Benjamin Peterson29060642009-01-31 22:14:21 +00002474 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002475 return NULL;
2476}
2477
Alexander Belopolsky40018472011-02-26 01:02:56 +00002478PyObject *
2479PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002480 const char *encoding,
2481 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002482{
2483 PyObject *v;
2484
2485 if (!PyUnicode_Check(unicode)) {
2486 PyErr_BadArgument();
2487 goto onError;
2488 }
2489
2490 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002491 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002492
2493 /* Decode via the codec registry */
2494 v = PyCodec_Decode(unicode, encoding, errors);
2495 if (v == NULL)
2496 goto onError;
2497 if (!PyUnicode_Check(v)) {
2498 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002499 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002500 Py_TYPE(v)->tp_name);
2501 Py_DECREF(v);
2502 goto onError;
2503 }
2504 return v;
2505
Benjamin Peterson29060642009-01-31 22:14:21 +00002506 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002507 return NULL;
2508}
2509
Alexander Belopolsky40018472011-02-26 01:02:56 +00002510PyObject *
2511PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002512 Py_ssize_t size,
2513 const char *encoding,
2514 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002515{
2516 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002517
Guido van Rossumd57fd912000-03-10 22:53:23 +00002518 unicode = PyUnicode_FromUnicode(s, size);
2519 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002521 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2522 Py_DECREF(unicode);
2523 return v;
2524}
2525
Alexander Belopolsky40018472011-02-26 01:02:56 +00002526PyObject *
2527PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002528 const char *encoding,
2529 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002530{
2531 PyObject *v;
2532
2533 if (!PyUnicode_Check(unicode)) {
2534 PyErr_BadArgument();
2535 goto onError;
2536 }
2537
2538 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002539 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002540
2541 /* Encode via the codec registry */
2542 v = PyCodec_Encode(unicode, encoding, errors);
2543 if (v == NULL)
2544 goto onError;
2545 return v;
2546
Benjamin Peterson29060642009-01-31 22:14:21 +00002547 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002548 return NULL;
2549}
2550
Victor Stinnerad158722010-10-27 00:25:46 +00002551PyObject *
2552PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002553{
Victor Stinner99b95382011-07-04 14:23:54 +02002554#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002555 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2556 PyUnicode_GET_SIZE(unicode),
2557 NULL);
2558#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002560#else
Victor Stinner793b5312011-04-27 00:24:21 +02002561 PyInterpreterState *interp = PyThreadState_GET()->interp;
2562 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2563 cannot use it to encode and decode filenames before it is loaded. Load
2564 the Python codec requires to encode at least its own filename. Use the C
2565 version of the locale codec until the codec registry is initialized and
2566 the Python codec is loaded.
2567
2568 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2569 cannot only rely on it: check also interp->fscodec_initialized for
2570 subinterpreters. */
2571 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002572 return PyUnicode_AsEncodedString(unicode,
2573 Py_FileSystemDefaultEncoding,
2574 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002575 }
2576 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002577 /* locale encoding with surrogateescape */
2578 wchar_t *wchar;
2579 char *bytes;
2580 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002581 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002582
2583 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2584 if (wchar == NULL)
2585 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002586 bytes = _Py_wchar2char(wchar, &error_pos);
2587 if (bytes == NULL) {
2588 if (error_pos != (size_t)-1) {
2589 char *errmsg = strerror(errno);
2590 PyObject *exc = NULL;
2591 if (errmsg == NULL)
2592 errmsg = "Py_wchar2char() failed";
2593 raise_encode_exception(&exc,
2594 "filesystemencoding",
2595 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2596 error_pos, error_pos+1,
2597 errmsg);
2598 Py_XDECREF(exc);
2599 }
2600 else
2601 PyErr_NoMemory();
2602 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002603 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002604 }
2605 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002606
2607 bytes_obj = PyBytes_FromString(bytes);
2608 PyMem_Free(bytes);
2609 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00002610 }
Victor Stinnerad158722010-10-27 00:25:46 +00002611#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00002612}
2613
Alexander Belopolsky40018472011-02-26 01:02:56 +00002614PyObject *
2615PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002616 const char *encoding,
2617 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002618{
2619 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00002620 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00002621
Guido van Rossumd57fd912000-03-10 22:53:23 +00002622 if (!PyUnicode_Check(unicode)) {
2623 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002624 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002625 }
Fred Drakee4315f52000-05-09 19:53:39 +00002626
Victor Stinner2f283c22011-03-02 01:21:46 +00002627 if (encoding == NULL) {
2628 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002630 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002631 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00002632 }
Fred Drakee4315f52000-05-09 19:53:39 +00002633
2634 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002635 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002636 if ((strcmp(lower, "utf-8") == 0) ||
2637 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00002638 {
Victor Stinner2f283c22011-03-02 01:21:46 +00002639 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002641 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00002643 }
Victor Stinner37296e82010-06-10 13:36:23 +00002644 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002645 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002646 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002647 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002648#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002649 else if (strcmp(lower, "mbcs") == 0)
2650 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2651 PyUnicode_GET_SIZE(unicode),
2652 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002653#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002654 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00002656 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002657
2658 /* Encode via the codec registry */
2659 v = PyCodec_Encode(unicode, encoding, errors);
2660 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002661 return NULL;
2662
2663 /* The normal path */
2664 if (PyBytes_Check(v))
2665 return v;
2666
2667 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002668 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002669 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002670 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002671
2672 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
2673 "encoder %s returned bytearray instead of bytes",
2674 encoding);
2675 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002676 Py_DECREF(v);
2677 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002678 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002679
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002680 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
2681 Py_DECREF(v);
2682 return b;
2683 }
2684
2685 PyErr_Format(PyExc_TypeError,
2686 "encoder did not return a bytes object (type=%.400s)",
2687 Py_TYPE(v)->tp_name);
2688 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002689 return NULL;
2690}
2691
Alexander Belopolsky40018472011-02-26 01:02:56 +00002692PyObject *
2693PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002694 const char *encoding,
2695 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002696{
2697 PyObject *v;
2698
2699 if (!PyUnicode_Check(unicode)) {
2700 PyErr_BadArgument();
2701 goto onError;
2702 }
2703
2704 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002705 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002706
2707 /* Encode via the codec registry */
2708 v = PyCodec_Encode(unicode, encoding, errors);
2709 if (v == NULL)
2710 goto onError;
2711 if (!PyUnicode_Check(v)) {
2712 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002713 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002714 Py_TYPE(v)->tp_name);
2715 Py_DECREF(v);
2716 goto onError;
2717 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002718 return v;
Tim Petersced69f82003-09-16 20:30:58 +00002719
Benjamin Peterson29060642009-01-31 22:14:21 +00002720 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721 return NULL;
2722}
2723
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002724PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00002725PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002726 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00002727 return PyUnicode_DecodeFSDefaultAndSize(s, size);
2728}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002729
Christian Heimes5894ba72007-11-04 11:43:14 +00002730PyObject*
2731PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
2732{
Victor Stinner99b95382011-07-04 14:23:54 +02002733#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002734 return PyUnicode_DecodeMBCS(s, size, NULL);
2735#elif defined(__APPLE__)
2736 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
2737#else
Victor Stinner793b5312011-04-27 00:24:21 +02002738 PyInterpreterState *interp = PyThreadState_GET()->interp;
2739 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2740 cannot use it to encode and decode filenames before it is loaded. Load
2741 the Python codec requires to encode at least its own filename. Use the C
2742 version of the locale codec until the codec registry is initialized and
2743 the Python codec is loaded.
2744
2745 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2746 cannot only rely on it: check also interp->fscodec_initialized for
2747 subinterpreters. */
2748 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002749 return PyUnicode_Decode(s, size,
2750 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00002751 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002752 }
2753 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002754 /* locale encoding with surrogateescape */
2755 wchar_t *wchar;
2756 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00002757 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002758
2759 if (s[size] != '\0' || size != strlen(s)) {
2760 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2761 return NULL;
2762 }
2763
Victor Stinner168e1172010-10-16 23:16:16 +00002764 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002765 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00002766 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002767
Victor Stinner168e1172010-10-16 23:16:16 +00002768 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002769 PyMem_Free(wchar);
2770 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002771 }
Victor Stinnerad158722010-10-27 00:25:46 +00002772#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002773}
2774
Martin v. Löwis011e8422009-05-05 04:43:17 +00002775
2776int
2777PyUnicode_FSConverter(PyObject* arg, void* addr)
2778{
2779 PyObject *output = NULL;
2780 Py_ssize_t size;
2781 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002782 if (arg == NULL) {
2783 Py_DECREF(*(PyObject**)addr);
2784 return 1;
2785 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00002786 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00002787 output = arg;
2788 Py_INCREF(output);
2789 }
2790 else {
2791 arg = PyUnicode_FromObject(arg);
2792 if (!arg)
2793 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002794 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002795 Py_DECREF(arg);
2796 if (!output)
2797 return 0;
2798 if (!PyBytes_Check(output)) {
2799 Py_DECREF(output);
2800 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
2801 return 0;
2802 }
2803 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00002804 size = PyBytes_GET_SIZE(output);
2805 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002806 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05002807 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00002808 Py_DECREF(output);
2809 return 0;
2810 }
2811 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002812 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00002813}
2814
2815
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002816int
2817PyUnicode_FSDecoder(PyObject* arg, void* addr)
2818{
2819 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002820 if (arg == NULL) {
2821 Py_DECREF(*(PyObject**)addr);
2822 return 1;
2823 }
2824 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 if (PyUnicode_READY(arg))
2826 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002827 output = arg;
2828 Py_INCREF(output);
2829 }
2830 else {
2831 arg = PyBytes_FromObject(arg);
2832 if (!arg)
2833 return 0;
2834 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
2835 PyBytes_GET_SIZE(arg));
2836 Py_DECREF(arg);
2837 if (!output)
2838 return 0;
2839 if (!PyUnicode_Check(output)) {
2840 Py_DECREF(output);
2841 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
2842 return 0;
2843 }
2844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
2846 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002847 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2848 Py_DECREF(output);
2849 return 0;
2850 }
2851 *(PyObject**)addr = output;
2852 return Py_CLEANUP_SUPPORTED;
2853}
2854
2855
Martin v. Löwis5b222132007-06-10 09:51:05 +00002856char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002857PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002858{
Christian Heimesf3863112007-11-22 07:46:41 +00002859 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002860 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
2861
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00002862 if (!PyUnicode_Check(unicode)) {
2863 PyErr_BadArgument();
2864 return NULL;
2865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002866 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002867 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002869 if (PyUnicode_UTF8(unicode) == NULL) {
2870 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002871 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
2872 if (bytes == NULL)
2873 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002874 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
2875 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002876 Py_DECREF(bytes);
2877 return NULL;
2878 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002879 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
2880 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002881 Py_DECREF(bytes);
2882 }
2883
2884 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02002885 *psize = PyUnicode_UTF8_LENGTH(unicode);
2886 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002887}
2888
2889char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002890PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00002891{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002892 return PyUnicode_AsUTF8AndSize(unicode, NULL);
2893}
2894
2895#ifdef Py_DEBUG
2896int unicode_as_unicode_calls = 0;
2897#endif
2898
2899
2900Py_UNICODE *
2901PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
2902{
2903 PyUnicodeObject *u;
2904 const unsigned char *one_byte;
2905#if SIZEOF_WCHAR_T == 4
2906 const Py_UCS2 *two_bytes;
2907#else
2908 const Py_UCS4 *four_bytes;
2909 const Py_UCS4 *ucs4_end;
2910 Py_ssize_t num_surrogates;
2911#endif
2912 wchar_t *w;
2913 wchar_t *wchar_end;
2914
2915 if (!PyUnicode_Check(unicode)) {
2916 PyErr_BadArgument();
2917 return NULL;
2918 }
2919 u = (PyUnicodeObject*)unicode;
2920 if (_PyUnicode_WSTR(u) == NULL) {
2921 /* Non-ASCII compact unicode object */
2922 assert(_PyUnicode_KIND(u) != 0);
2923 assert(PyUnicode_IS_READY(u));
2924
2925#ifdef Py_DEBUG
2926 ++unicode_as_unicode_calls;
2927#endif
2928
2929 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
2930#if SIZEOF_WCHAR_T == 2
2931 four_bytes = PyUnicode_4BYTE_DATA(u);
2932 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
2933 num_surrogates = 0;
2934
2935 for (; four_bytes < ucs4_end; ++four_bytes) {
2936 if (*four_bytes > 0xFFFF)
2937 ++num_surrogates;
2938 }
2939
2940 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
2941 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
2942 if (!_PyUnicode_WSTR(u)) {
2943 PyErr_NoMemory();
2944 return NULL;
2945 }
2946 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
2947
2948 w = _PyUnicode_WSTR(u);
2949 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
2950 four_bytes = PyUnicode_4BYTE_DATA(u);
2951 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
2952 if (*four_bytes > 0xFFFF) {
2953 /* encode surrogate pair in this case */
2954 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
2955 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
2956 }
2957 else
2958 *w = *four_bytes;
2959
2960 if (w > wchar_end) {
2961 assert(0 && "Miscalculated string end");
2962 }
2963 }
2964 *w = 0;
2965#else
2966 /* sizeof(wchar_t) == 4 */
2967 Py_FatalError("Impossible unicode object state, wstr and str "
2968 "should share memory already.");
2969 return NULL;
2970#endif
2971 }
2972 else {
2973 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
2974 (_PyUnicode_LENGTH(u) + 1));
2975 if (!_PyUnicode_WSTR(u)) {
2976 PyErr_NoMemory();
2977 return NULL;
2978 }
2979 if (!PyUnicode_IS_COMPACT_ASCII(u))
2980 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
2981 w = _PyUnicode_WSTR(u);
2982 wchar_end = w + _PyUnicode_LENGTH(u);
2983
2984 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
2985 one_byte = PyUnicode_1BYTE_DATA(u);
2986 for (; w < wchar_end; ++one_byte, ++w)
2987 *w = *one_byte;
2988 /* null-terminate the wstr */
2989 *w = 0;
2990 }
2991 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
2992#if SIZEOF_WCHAR_T == 4
2993 two_bytes = PyUnicode_2BYTE_DATA(u);
2994 for (; w < wchar_end; ++two_bytes, ++w)
2995 *w = *two_bytes;
2996 /* null-terminate the wstr */
2997 *w = 0;
2998#else
2999 /* sizeof(wchar_t) == 2 */
3000 PyObject_FREE(_PyUnicode_WSTR(u));
3001 _PyUnicode_WSTR(u) = NULL;
3002 Py_FatalError("Impossible unicode object state, wstr "
3003 "and str should share memory already.");
3004 return NULL;
3005#endif
3006 }
3007 else {
3008 assert(0 && "This should never happen.");
3009 }
3010 }
3011 }
3012 if (size != NULL)
3013 *size = PyUnicode_WSTR_LENGTH(u);
3014 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003015}
3016
Alexander Belopolsky40018472011-02-26 01:02:56 +00003017Py_UNICODE *
3018PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003019{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003020 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021}
3022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003023
Alexander Belopolsky40018472011-02-26 01:02:56 +00003024Py_ssize_t
3025PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003026{
3027 if (!PyUnicode_Check(unicode)) {
3028 PyErr_BadArgument();
3029 goto onError;
3030 }
3031 return PyUnicode_GET_SIZE(unicode);
3032
Benjamin Peterson29060642009-01-31 22:14:21 +00003033 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003034 return -1;
3035}
3036
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003037Py_ssize_t
3038PyUnicode_GetLength(PyObject *unicode)
3039{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003040 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003041 PyErr_BadArgument();
3042 return -1;
3043 }
3044
3045 return PyUnicode_GET_LENGTH(unicode);
3046}
3047
3048Py_UCS4
3049PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3050{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003051 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3052 PyErr_BadArgument();
3053 return (Py_UCS4)-1;
3054 }
3055 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3056 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003057 return (Py_UCS4)-1;
3058 }
3059 return PyUnicode_READ_CHAR(unicode, index);
3060}
3061
3062int
3063PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3064{
3065 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003066 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003067 return -1;
3068 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003069 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3070 PyErr_SetString(PyExc_IndexError, "string index out of range");
3071 return -1;
3072 }
3073 if (_PyUnicode_Dirty(unicode))
3074 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003075 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3076 index, ch);
3077 return 0;
3078}
3079
Alexander Belopolsky40018472011-02-26 01:02:56 +00003080const char *
3081PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003082{
Victor Stinner42cb4622010-09-01 19:39:01 +00003083 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003084}
3085
Victor Stinner554f3f02010-06-16 23:33:54 +00003086/* create or adjust a UnicodeDecodeError */
3087static void
3088make_decode_exception(PyObject **exceptionObject,
3089 const char *encoding,
3090 const char *input, Py_ssize_t length,
3091 Py_ssize_t startpos, Py_ssize_t endpos,
3092 const char *reason)
3093{
3094 if (*exceptionObject == NULL) {
3095 *exceptionObject = PyUnicodeDecodeError_Create(
3096 encoding, input, length, startpos, endpos, reason);
3097 }
3098 else {
3099 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3100 goto onError;
3101 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3102 goto onError;
3103 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3104 goto onError;
3105 }
3106 return;
3107
3108onError:
3109 Py_DECREF(*exceptionObject);
3110 *exceptionObject = NULL;
3111}
3112
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003113/* error handling callback helper:
3114 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003115 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003116 and adjust various state variables.
3117 return 0 on success, -1 on error
3118*/
3119
Alexander Belopolsky40018472011-02-26 01:02:56 +00003120static int
3121unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003122 const char *encoding, const char *reason,
3123 const char **input, const char **inend, Py_ssize_t *startinpos,
3124 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3125 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003126{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003127 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003128
3129 PyObject *restuple = NULL;
3130 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003131 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003132 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003133 Py_ssize_t requiredsize;
3134 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003135 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003136 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003137 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003138 int res = -1;
3139
3140 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003141 *errorHandler = PyCodec_LookupError(errors);
3142 if (*errorHandler == NULL)
3143 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003144 }
3145
Victor Stinner554f3f02010-06-16 23:33:54 +00003146 make_decode_exception(exceptionObject,
3147 encoding,
3148 *input, *inend - *input,
3149 *startinpos, *endinpos,
3150 reason);
3151 if (*exceptionObject == NULL)
3152 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003153
3154 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3155 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003156 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003157 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003158 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003159 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003160 }
3161 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003163
3164 /* Copy back the bytes variables, which might have been modified by the
3165 callback */
3166 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3167 if (!inputobj)
3168 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003169 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003170 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003171 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003172 *input = PyBytes_AS_STRING(inputobj);
3173 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003174 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003175 /* we can DECREF safely, as the exception has another reference,
3176 so the object won't go away. */
3177 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003178
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003179 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003180 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003181 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003182 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3183 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003184 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003185
3186 /* need more space? (at least enough for what we
3187 have+the replacement+the rest of the string (starting
3188 at the new input position), so we won't have to check space
3189 when there are no errors in the rest of the string) */
3190 repptr = PyUnicode_AS_UNICODE(repunicode);
3191 repsize = PyUnicode_GET_SIZE(repunicode);
3192 requiredsize = *outpos + repsize + insize-newpos;
3193 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003194 if (requiredsize<2*outsize)
3195 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003196 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003197 goto onError;
3198 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003199 }
3200 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003201 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003202 Py_UNICODE_COPY(*outptr, repptr, repsize);
3203 *outptr += repsize;
3204 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003205
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003206 /* we made it! */
3207 res = 0;
3208
Benjamin Peterson29060642009-01-31 22:14:21 +00003209 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003210 Py_XDECREF(restuple);
3211 return res;
3212}
3213
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003214/* --- UTF-7 Codec -------------------------------------------------------- */
3215
Antoine Pitrou244651a2009-05-04 18:56:13 +00003216/* See RFC2152 for details. We encode conservatively and decode liberally. */
3217
3218/* Three simple macros defining base-64. */
3219
3220/* Is c a base-64 character? */
3221
3222#define IS_BASE64(c) \
3223 (((c) >= 'A' && (c) <= 'Z') || \
3224 ((c) >= 'a' && (c) <= 'z') || \
3225 ((c) >= '0' && (c) <= '9') || \
3226 (c) == '+' || (c) == '/')
3227
3228/* given that c is a base-64 character, what is its base-64 value? */
3229
3230#define FROM_BASE64(c) \
3231 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3232 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3233 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3234 (c) == '+' ? 62 : 63)
3235
3236/* What is the base-64 character of the bottom 6 bits of n? */
3237
3238#define TO_BASE64(n) \
3239 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3240
3241/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3242 * decoded as itself. We are permissive on decoding; the only ASCII
3243 * byte not decoding to itself is the + which begins a base64
3244 * string. */
3245
3246#define DECODE_DIRECT(c) \
3247 ((c) <= 127 && (c) != '+')
3248
3249/* The UTF-7 encoder treats ASCII characters differently according to
3250 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3251 * the above). See RFC2152. This array identifies these different
3252 * sets:
3253 * 0 : "Set D"
3254 * alphanumeric and '(),-./:?
3255 * 1 : "Set O"
3256 * !"#$%&*;<=>@[]^_`{|}
3257 * 2 : "whitespace"
3258 * ht nl cr sp
3259 * 3 : special (must be base64 encoded)
3260 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3261 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003262
Tim Petersced69f82003-09-16 20:30:58 +00003263static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003264char utf7_category[128] = {
3265/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3266 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3267/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3268 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3269/* sp ! " # $ % & ' ( ) * + , - . / */
3270 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3271/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3272 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3273/* @ A B C D E F G H I J K L M N O */
3274 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3275/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3276 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3277/* ` a b c d e f g h i j k l m n o */
3278 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3279/* p q r s t u v w x y z { | } ~ del */
3280 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003281};
3282
Antoine Pitrou244651a2009-05-04 18:56:13 +00003283/* ENCODE_DIRECT: this character should be encoded as itself. The
3284 * answer depends on whether we are encoding set O as itself, and also
3285 * on whether we are encoding whitespace as itself. RFC2152 makes it
3286 * clear that the answers to these questions vary between
3287 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003288
Antoine Pitrou244651a2009-05-04 18:56:13 +00003289#define ENCODE_DIRECT(c, directO, directWS) \
3290 ((c) < 128 && (c) > 0 && \
3291 ((utf7_category[(c)] == 0) || \
3292 (directWS && (utf7_category[(c)] == 2)) || \
3293 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003294
Alexander Belopolsky40018472011-02-26 01:02:56 +00003295PyObject *
3296PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003297 Py_ssize_t size,
3298 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003299{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003300 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3301}
3302
Antoine Pitrou244651a2009-05-04 18:56:13 +00003303/* The decoder. The only state we preserve is our read position,
3304 * i.e. how many characters we have consumed. So if we end in the
3305 * middle of a shift sequence we have to back off the read position
3306 * and the output to the beginning of the sequence, otherwise we lose
3307 * all the shift state (seen bits, number of bits seen, high
3308 * surrogate). */
3309
Alexander Belopolsky40018472011-02-26 01:02:56 +00003310PyObject *
3311PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003312 Py_ssize_t size,
3313 const char *errors,
3314 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003315{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003316 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003317 Py_ssize_t startinpos;
3318 Py_ssize_t endinpos;
3319 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003320 const char *e;
3321 PyUnicodeObject *unicode;
3322 Py_UNICODE *p;
3323 const char *errmsg = "";
3324 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003325 Py_UNICODE *shiftOutStart;
3326 unsigned int base64bits = 0;
3327 unsigned long base64buffer = 0;
3328 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003329 PyObject *errorHandler = NULL;
3330 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003331
3332 unicode = _PyUnicode_New(size);
3333 if (!unicode)
3334 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003335 if (size == 0) {
3336 if (consumed)
3337 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003338 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003339 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003342 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003343 e = s + size;
3344
3345 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003346 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003347 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003348 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003349
Antoine Pitrou244651a2009-05-04 18:56:13 +00003350 if (inShift) { /* in a base-64 section */
3351 if (IS_BASE64(ch)) { /* consume a base-64 character */
3352 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3353 base64bits += 6;
3354 s++;
3355 if (base64bits >= 16) {
3356 /* we have enough bits for a UTF-16 value */
3357 Py_UNICODE outCh = (Py_UNICODE)
3358 (base64buffer >> (base64bits-16));
3359 base64bits -= 16;
3360 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3361 if (surrogate) {
3362 /* expecting a second surrogate */
3363 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3364#ifdef Py_UNICODE_WIDE
3365 *p++ = (((surrogate & 0x3FF)<<10)
3366 | (outCh & 0x3FF)) + 0x10000;
3367#else
3368 *p++ = surrogate;
3369 *p++ = outCh;
3370#endif
3371 surrogate = 0;
3372 }
3373 else {
3374 surrogate = 0;
3375 errmsg = "second surrogate missing";
3376 goto utf7Error;
3377 }
3378 }
3379 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3380 /* first surrogate */
3381 surrogate = outCh;
3382 }
3383 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3384 errmsg = "unexpected second surrogate";
3385 goto utf7Error;
3386 }
3387 else {
3388 *p++ = outCh;
3389 }
3390 }
3391 }
3392 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003393 inShift = 0;
3394 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003395 if (surrogate) {
3396 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003397 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003398 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003399 if (base64bits > 0) { /* left-over bits */
3400 if (base64bits >= 6) {
3401 /* We've seen at least one base-64 character */
3402 errmsg = "partial character in shift sequence";
3403 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003404 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003405 else {
3406 /* Some bits remain; they should be zero */
3407 if (base64buffer != 0) {
3408 errmsg = "non-zero padding bits in shift sequence";
3409 goto utf7Error;
3410 }
3411 }
3412 }
3413 if (ch != '-') {
3414 /* '-' is absorbed; other terminating
3415 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003416 *p++ = ch;
3417 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003418 }
3419 }
3420 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003421 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003422 s++; /* consume '+' */
3423 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003424 s++;
3425 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003426 }
3427 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003428 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003429 shiftOutStart = p;
3430 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003431 }
3432 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003433 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003434 *p++ = ch;
3435 s++;
3436 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003437 else {
3438 startinpos = s-starts;
3439 s++;
3440 errmsg = "unexpected special character";
3441 goto utf7Error;
3442 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003443 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003444utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003445 outpos = p-PyUnicode_AS_UNICODE(unicode);
3446 endinpos = s-starts;
3447 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003448 errors, &errorHandler,
3449 "utf7", errmsg,
3450 &starts, &e, &startinpos, &endinpos, &exc, &s,
3451 &unicode, &outpos, &p))
3452 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003453 }
3454
Antoine Pitrou244651a2009-05-04 18:56:13 +00003455 /* end of string */
3456
3457 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3458 /* if we're in an inconsistent state, that's an error */
3459 if (surrogate ||
3460 (base64bits >= 6) ||
3461 (base64bits > 0 && base64buffer != 0)) {
3462 outpos = p-PyUnicode_AS_UNICODE(unicode);
3463 endinpos = size;
3464 if (unicode_decode_call_errorhandler(
3465 errors, &errorHandler,
3466 "utf7", "unterminated shift sequence",
3467 &starts, &e, &startinpos, &endinpos, &exc, &s,
3468 &unicode, &outpos, &p))
3469 goto onError;
3470 if (s < e)
3471 goto restart;
3472 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003473 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003474
3475 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003476 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003477 if (inShift) {
3478 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003479 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003480 }
3481 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003482 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003483 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003484 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003485
Victor Stinnerfe226c02011-10-03 03:52:20 +02003486 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003487 goto onError;
3488
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003489 Py_XDECREF(errorHandler);
3490 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003491 if (PyUnicode_READY(unicode) == -1) {
3492 Py_DECREF(unicode);
3493 return NULL;
3494 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003495 return (PyObject *)unicode;
3496
Benjamin Peterson29060642009-01-31 22:14:21 +00003497 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003498 Py_XDECREF(errorHandler);
3499 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003500 Py_DECREF(unicode);
3501 return NULL;
3502}
3503
3504
Alexander Belopolsky40018472011-02-26 01:02:56 +00003505PyObject *
3506PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003507 Py_ssize_t size,
3508 int base64SetO,
3509 int base64WhiteSpace,
3510 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003511{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003512 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003513 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003514 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003515 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003516 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003517 unsigned int base64bits = 0;
3518 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003519 char * out;
3520 char * start;
3521
3522 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003523 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003524
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003525 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003526 return PyErr_NoMemory();
3527
Antoine Pitrou244651a2009-05-04 18:56:13 +00003528 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003529 if (v == NULL)
3530 return NULL;
3531
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003532 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003533 for (;i < size; ++i) {
3534 Py_UNICODE ch = s[i];
3535
Antoine Pitrou244651a2009-05-04 18:56:13 +00003536 if (inShift) {
3537 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3538 /* shifting out */
3539 if (base64bits) { /* output remaining bits */
3540 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3541 base64buffer = 0;
3542 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003543 }
3544 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003545 /* Characters not in the BASE64 set implicitly unshift the sequence
3546 so no '-' is required, except if the character is itself a '-' */
3547 if (IS_BASE64(ch) || ch == '-') {
3548 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003549 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003550 *out++ = (char) ch;
3551 }
3552 else {
3553 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003555 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003556 else { /* not in a shift sequence */
3557 if (ch == '+') {
3558 *out++ = '+';
3559 *out++ = '-';
3560 }
3561 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3562 *out++ = (char) ch;
3563 }
3564 else {
3565 *out++ = '+';
3566 inShift = 1;
3567 goto encode_char;
3568 }
3569 }
3570 continue;
3571encode_char:
3572#ifdef Py_UNICODE_WIDE
3573 if (ch >= 0x10000) {
3574 /* code first surrogate */
3575 base64bits += 16;
3576 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3577 while (base64bits >= 6) {
3578 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3579 base64bits -= 6;
3580 }
3581 /* prepare second surrogate */
3582 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3583 }
3584#endif
3585 base64bits += 16;
3586 base64buffer = (base64buffer << 16) | ch;
3587 while (base64bits >= 6) {
3588 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3589 base64bits -= 6;
3590 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003591 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003592 if (base64bits)
3593 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3594 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003595 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003596 if (_PyBytes_Resize(&v, out - start) < 0)
3597 return NULL;
3598 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003599}
3600
Antoine Pitrou244651a2009-05-04 18:56:13 +00003601#undef IS_BASE64
3602#undef FROM_BASE64
3603#undef TO_BASE64
3604#undef DECODE_DIRECT
3605#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003606
Guido van Rossumd57fd912000-03-10 22:53:23 +00003607/* --- UTF-8 Codec -------------------------------------------------------- */
3608
Tim Petersced69f82003-09-16 20:30:58 +00003609static
Guido van Rossumd57fd912000-03-10 22:53:23 +00003610char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00003611 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
3612 illegal prefix. See RFC 3629 for details */
3613 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
3614 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003615 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00003616 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3617 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3618 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3619 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00003620 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
3621 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 +00003622 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3623 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00003624 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
3625 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
3626 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
3627 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
3628 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 +00003629};
3630
Alexander Belopolsky40018472011-02-26 01:02:56 +00003631PyObject *
3632PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003633 Py_ssize_t size,
3634 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003635{
Walter Dörwald69652032004-09-07 20:24:22 +00003636 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3637}
3638
Antoine Pitrouab868312009-01-10 15:40:25 +00003639/* Mask to check or force alignment of a pointer to C 'long' boundaries */
3640#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
3641
3642/* Mask to quickly check whether a C 'long' contains a
3643 non-ASCII, UTF8-encoded char. */
3644#if (SIZEOF_LONG == 8)
3645# define ASCII_CHAR_MASK 0x8080808080808080L
3646#elif (SIZEOF_LONG == 4)
3647# define ASCII_CHAR_MASK 0x80808080L
3648#else
3649# error C 'long' size should be either 4 or 8!
3650#endif
3651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003652/* Scans a UTF-8 string and returns the maximum character to be expected,
3653 the size of the decoded unicode string and if any major errors were
3654 encountered.
3655
3656 This function does check basic UTF-8 sanity, it does however NOT CHECK
3657 if the string contains surrogates, and if all continuation bytes are
3658 within the correct ranges, these checks are performed in
3659 PyUnicode_DecodeUTF8Stateful.
3660
3661 If it sets has_errors to 1, it means the value of unicode_size and max_char
3662 will be bogus and you should not rely on useful information in them.
3663 */
3664static Py_UCS4
3665utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
3666 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
3667 int *has_errors)
3668{
3669 Py_ssize_t n;
3670 Py_ssize_t char_count = 0;
3671 Py_UCS4 max_char = 127, new_max;
3672 Py_UCS4 upper_bound;
3673 const unsigned char *p = (const unsigned char *)s;
3674 const unsigned char *end = p + string_size;
3675 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
3676 int err = 0;
3677
3678 for (; p < end && !err; ++p, ++char_count) {
3679 /* Only check value if it's not a ASCII char... */
3680 if (*p < 0x80) {
3681 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
3682 an explanation. */
3683 if (!((size_t) p & LONG_PTR_MASK)) {
3684 /* Help register allocation */
3685 register const unsigned char *_p = p;
3686 while (_p < aligned_end) {
3687 unsigned long value = *(unsigned long *) _p;
3688 if (value & ASCII_CHAR_MASK)
3689 break;
3690 _p += SIZEOF_LONG;
3691 char_count += SIZEOF_LONG;
3692 }
3693 p = _p;
3694 if (p == end)
3695 break;
3696 }
3697 }
3698 if (*p >= 0x80) {
3699 n = utf8_code_length[*p];
3700 new_max = max_char;
3701 switch (n) {
3702 /* invalid start byte */
3703 case 0:
3704 err = 1;
3705 break;
3706 case 2:
3707 /* Code points between 0x00FF and 0x07FF inclusive.
3708 Approximate the upper bound of the code point,
3709 if this flips over 255 we can be sure it will be more
3710 than 255 and the string will need 2 bytes per code coint,
3711 if it stays under or equal to 255, we can be sure 1 byte
3712 is enough.
3713 ((*p & 0b00011111) << 6) | 0b00111111 */
3714 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
3715 if (max_char < upper_bound)
3716 new_max = upper_bound;
3717 /* Ensure we track at least that we left ASCII space. */
3718 if (new_max < 128)
3719 new_max = 128;
3720 break;
3721 case 3:
3722 /* Between 0x0FFF and 0xFFFF inclusive, so values are
3723 always > 255 and <= 65535 and will always need 2 bytes. */
3724 if (max_char < 65535)
3725 new_max = 65535;
3726 break;
3727 case 4:
3728 /* Code point will be above 0xFFFF for sure in this case. */
3729 new_max = 65537;
3730 break;
3731 /* Internal error, this should be caught by the first if */
3732 case 1:
3733 default:
3734 assert(0 && "Impossible case in utf8_max_char_and_size");
3735 err = 1;
3736 }
3737 /* Instead of number of overall bytes for this code point,
3738 n containts the number of following bytes: */
3739 --n;
3740 /* Check if the follow up chars are all valid continuation bytes */
3741 if (n >= 1) {
3742 const unsigned char *cont;
3743 if ((p + n) >= end) {
3744 if (consumed == 0)
3745 /* incomplete data, non-incremental decoding */
3746 err = 1;
3747 break;
3748 }
3749 for (cont = p + 1; cont < (p + n); ++cont) {
3750 if ((*cont & 0xc0) != 0x80) {
3751 err = 1;
3752 break;
3753 }
3754 }
3755 p += n;
3756 }
3757 else
3758 err = 1;
3759 max_char = new_max;
3760 }
3761 }
3762
3763 if (unicode_size)
3764 *unicode_size = char_count;
3765 if (has_errors)
3766 *has_errors = err;
3767 return max_char;
3768}
3769
3770/* Similar to PyUnicode_WRITE but can also write into wstr field
3771 of the legacy unicode representation */
3772#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
3773 do { \
3774 const int k_ = (kind); \
3775 if (k_ == PyUnicode_WCHAR_KIND) \
3776 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
3777 else if (k_ == PyUnicode_1BYTE_KIND) \
3778 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
3779 else if (k_ == PyUnicode_2BYTE_KIND) \
3780 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
3781 else \
3782 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
3783 } while (0)
3784
Alexander Belopolsky40018472011-02-26 01:02:56 +00003785PyObject *
3786PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003787 Py_ssize_t size,
3788 const char *errors,
3789 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003790{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003791 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003792 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00003793 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003794 Py_ssize_t startinpos;
3795 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00003796 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003797 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003798 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003799 PyObject *errorHandler = NULL;
3800 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 Py_UCS4 maxchar = 0;
3802 Py_ssize_t unicode_size;
3803 Py_ssize_t i;
3804 int kind;
3805 void *data;
3806 int has_errors;
3807 Py_UNICODE *error_outptr;
3808#if SIZEOF_WCHAR_T == 2
3809 Py_ssize_t wchar_offset = 0;
3810#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003811
Walter Dörwald69652032004-09-07 20:24:22 +00003812 if (size == 0) {
3813 if (consumed)
3814 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00003816 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
3818 consumed, &has_errors);
3819 if (has_errors) {
3820 unicode = _PyUnicode_New(size);
3821 if (!unicode)
3822 return NULL;
3823 kind = PyUnicode_WCHAR_KIND;
3824 data = PyUnicode_AS_UNICODE(unicode);
3825 assert(data != NULL);
3826 }
3827 else {
3828 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
3829 if (!unicode)
3830 return NULL;
3831 /* When the string is ASCII only, just use memcpy and return.
3832 unicode_size may be != size if there is an incomplete UTF-8
3833 sequence at the end of the ASCII block. */
3834 if (maxchar < 128 && size == unicode_size) {
3835 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
3836 return (PyObject *)unicode;
3837 }
3838 kind = PyUnicode_KIND(unicode);
3839 data = PyUnicode_DATA(unicode);
3840 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003841 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003843 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00003844 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003845
3846 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003847 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003848
3849 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00003850 /* Fast path for runs of ASCII characters. Given that common UTF-8
3851 input will consist of an overwhelming majority of ASCII
3852 characters, we try to optimize for this case by checking
3853 as many characters as a C 'long' can contain.
3854 First, check if we can do an aligned read, as most CPUs have
3855 a penalty for unaligned reads.
3856 */
3857 if (!((size_t) s & LONG_PTR_MASK)) {
3858 /* Help register allocation */
3859 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003861 while (_s < aligned_end) {
3862 /* Read a whole long at a time (either 4 or 8 bytes),
3863 and do a fast unrolled copy if it only contains ASCII
3864 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 unsigned long value = *(unsigned long *) _s;
3866 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00003867 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
3869 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
3870 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
3871 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003872#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003873 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
3874 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
3875 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
3876 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00003877#endif
3878 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003879 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00003880 }
3881 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00003883 if (s == e)
3884 break;
3885 ch = (unsigned char)*s;
3886 }
3887 }
3888
3889 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003891 s++;
3892 continue;
3893 }
3894
3895 n = utf8_code_length[ch];
3896
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003897 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003898 if (consumed)
3899 break;
3900 else {
3901 errmsg = "unexpected end of data";
3902 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003903 endinpos = startinpos+1;
3904 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
3905 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003906 goto utf8Error;
3907 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003909
3910 switch (n) {
3911
3912 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00003913 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003914 startinpos = s-starts;
3915 endinpos = startinpos+1;
3916 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003917
3918 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003919 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00003920 startinpos = s-starts;
3921 endinpos = startinpos+1;
3922 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003923
3924 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003925 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00003926 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003927 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003928 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00003929 goto utf8Error;
3930 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003931 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003932 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003933 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003934 break;
3935
3936 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00003937 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
3938 will result in surrogates in range d800-dfff. Surrogates are
3939 not valid UTF-8 so they are rejected.
3940 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
3941 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00003942 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003943 (s[2] & 0xc0) != 0x80 ||
3944 ((unsigned char)s[0] == 0xE0 &&
3945 (unsigned char)s[1] < 0xA0) ||
3946 ((unsigned char)s[0] == 0xED &&
3947 (unsigned char)s[1] > 0x9F)) {
3948 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003949 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003950 endinpos = startinpos + 1;
3951
3952 /* if s[1] first two bits are 1 and 0, then the invalid
3953 continuation byte is s[2], so increment endinpos by 1,
3954 if not, s[1] is invalid and endinpos doesn't need to
3955 be incremented. */
3956 if ((s[1] & 0xC0) == 0x80)
3957 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00003958 goto utf8Error;
3959 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003960 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00003961 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003963 break;
3964
3965 case 4:
3966 if ((s[1] & 0xc0) != 0x80 ||
3967 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00003968 (s[3] & 0xc0) != 0x80 ||
3969 ((unsigned char)s[0] == 0xF0 &&
3970 (unsigned char)s[1] < 0x90) ||
3971 ((unsigned char)s[0] == 0xF4 &&
3972 (unsigned char)s[1] > 0x8F)) {
3973 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00003974 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00003975 endinpos = startinpos + 1;
3976 if ((s[1] & 0xC0) == 0x80) {
3977 endinpos++;
3978 if ((s[2] & 0xC0) == 0x80)
3979 endinpos++;
3980 }
Benjamin Peterson29060642009-01-31 22:14:21 +00003981 goto utf8Error;
3982 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003983 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00003984 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
3985 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
3986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 /* If the string is flexible or we have native UCS-4, write
3988 directly.. */
3989 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
3990 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00003991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 else {
3993 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00003994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003995 /* translate from 10000..10FFFF to 0..FFFF */
3996 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00003997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 /* high surrogate = top 10 bits added to D800 */
3999 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4000 (Py_UNICODE)(0xD800 + (ch >> 10)));
4001
4002 /* low surrogate = bottom 10 bits added to DC00 */
4003 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4004 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4005 }
4006#if SIZEOF_WCHAR_T == 2
4007 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004008#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004009 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004010 }
4011 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004012 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004013
Benjamin Peterson29060642009-01-31 22:14:21 +00004014 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 /* If this is not yet a resizable string, make it one.. */
4016 if (kind != PyUnicode_WCHAR_KIND) {
4017 const Py_UNICODE *u;
4018 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4019 if (!new_unicode)
4020 goto onError;
4021 u = PyUnicode_AsUnicode((PyObject *)unicode);
4022 if (!u)
4023 goto onError;
4024#if SIZEOF_WCHAR_T == 2
4025 i += wchar_offset;
4026#endif
4027 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4028 Py_DECREF(unicode);
4029 unicode = new_unicode;
4030 kind = 0;
4031 data = PyUnicode_AS_UNICODE(new_unicode);
4032 assert(data != NULL);
4033 }
4034 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 if (unicode_decode_call_errorhandler(
4036 errors, &errorHandler,
4037 "utf8", errmsg,
4038 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004039 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041 /* Update data because unicode_decode_call_errorhandler might have
4042 re-created or resized the unicode object. */
4043 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 /* Ensure the unicode_size calculation above was correct: */
4047 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4048
Walter Dörwald69652032004-09-07 20:24:22 +00004049 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004050 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004052 /* Adjust length and ready string when it contained errors and
4053 is of the old resizable kind. */
4054 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02004055 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0 ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056 PyUnicode_READY(unicode) == -1)
4057 goto onError;
4058 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004059
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 Py_XDECREF(errorHandler);
4061 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004062 if (PyUnicode_READY(unicode) == -1) {
4063 Py_DECREF(unicode);
4064 return NULL;
4065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004066 return (PyObject *)unicode;
4067
Benjamin Peterson29060642009-01-31 22:14:21 +00004068 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069 Py_XDECREF(errorHandler);
4070 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004071 Py_DECREF(unicode);
4072 return NULL;
4073}
4074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004075#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004076
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004077#ifdef __APPLE__
4078
4079/* Simplified UTF-8 decoder using surrogateescape error handler,
4080 used to decode the command line arguments on Mac OS X. */
4081
4082wchar_t*
4083_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4084{
4085 int n;
4086 const char *e;
4087 wchar_t *unicode, *p;
4088
4089 /* Note: size will always be longer than the resulting Unicode
4090 character count */
4091 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4092 PyErr_NoMemory();
4093 return NULL;
4094 }
4095 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4096 if (!unicode)
4097 return NULL;
4098
4099 /* Unpack UTF-8 encoded data */
4100 p = unicode;
4101 e = s + size;
4102 while (s < e) {
4103 Py_UCS4 ch = (unsigned char)*s;
4104
4105 if (ch < 0x80) {
4106 *p++ = (wchar_t)ch;
4107 s++;
4108 continue;
4109 }
4110
4111 n = utf8_code_length[ch];
4112 if (s + n > e) {
4113 goto surrogateescape;
4114 }
4115
4116 switch (n) {
4117 case 0:
4118 case 1:
4119 goto surrogateescape;
4120
4121 case 2:
4122 if ((s[1] & 0xc0) != 0x80)
4123 goto surrogateescape;
4124 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4125 assert ((ch > 0x007F) && (ch <= 0x07FF));
4126 *p++ = (wchar_t)ch;
4127 break;
4128
4129 case 3:
4130 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4131 will result in surrogates in range d800-dfff. Surrogates are
4132 not valid UTF-8 so they are rejected.
4133 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4134 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4135 if ((s[1] & 0xc0) != 0x80 ||
4136 (s[2] & 0xc0) != 0x80 ||
4137 ((unsigned char)s[0] == 0xE0 &&
4138 (unsigned char)s[1] < 0xA0) ||
4139 ((unsigned char)s[0] == 0xED &&
4140 (unsigned char)s[1] > 0x9F)) {
4141
4142 goto surrogateescape;
4143 }
4144 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4145 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004146 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004147 break;
4148
4149 case 4:
4150 if ((s[1] & 0xc0) != 0x80 ||
4151 (s[2] & 0xc0) != 0x80 ||
4152 (s[3] & 0xc0) != 0x80 ||
4153 ((unsigned char)s[0] == 0xF0 &&
4154 (unsigned char)s[1] < 0x90) ||
4155 ((unsigned char)s[0] == 0xF4 &&
4156 (unsigned char)s[1] > 0x8F)) {
4157 goto surrogateescape;
4158 }
4159 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4160 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4161 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4162
4163#if SIZEOF_WCHAR_T == 4
4164 *p++ = (wchar_t)ch;
4165#else
4166 /* compute and append the two surrogates: */
4167
4168 /* translate from 10000..10FFFF to 0..FFFF */
4169 ch -= 0x10000;
4170
4171 /* high surrogate = top 10 bits added to D800 */
4172 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4173
4174 /* low surrogate = bottom 10 bits added to DC00 */
4175 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4176#endif
4177 break;
4178 }
4179 s += n;
4180 continue;
4181
4182 surrogateescape:
4183 *p++ = 0xDC00 + ch;
4184 s++;
4185 }
4186 *p = L'\0';
4187 return unicode;
4188}
4189
4190#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004192/* Primary internal function which creates utf8 encoded bytes objects.
4193
4194 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004195 and allocate exactly as much space needed at the end. Else allocate the
4196 maximum possible needed (4 result bytes per Unicode character), and return
4197 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004198*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004199PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004200_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004201{
Tim Peters602f7402002-04-27 18:03:26 +00004202#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004203
Guido van Rossum98297ee2007-11-06 21:34:58 +00004204 Py_ssize_t i; /* index into s of next input byte */
4205 PyObject *result; /* result string object */
4206 char *p; /* next free byte in output buffer */
4207 Py_ssize_t nallocated; /* number of result bytes allocated */
4208 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004209 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004210 PyObject *errorHandler = NULL;
4211 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004212 int kind;
4213 void *data;
4214 Py_ssize_t size;
4215 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4216#if SIZEOF_WCHAR_T == 2
4217 Py_ssize_t wchar_offset = 0;
4218#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004220 if (!PyUnicode_Check(unicode)) {
4221 PyErr_BadArgument();
4222 return NULL;
4223 }
4224
4225 if (PyUnicode_READY(unicode) == -1)
4226 return NULL;
4227
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004228 if (PyUnicode_UTF8(unicode))
4229 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4230 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004231
4232 kind = PyUnicode_KIND(unicode);
4233 data = PyUnicode_DATA(unicode);
4234 size = PyUnicode_GET_LENGTH(unicode);
4235
Tim Peters602f7402002-04-27 18:03:26 +00004236 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004237
Tim Peters602f7402002-04-27 18:03:26 +00004238 if (size <= MAX_SHORT_UNICHARS) {
4239 /* Write into the stack buffer; nallocated can't overflow.
4240 * At the end, we'll allocate exactly as much heap space as it
4241 * turns out we need.
4242 */
4243 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004244 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004245 p = stackbuf;
4246 }
4247 else {
4248 /* Overallocate on the heap, and give the excess back at the end. */
4249 nallocated = size * 4;
4250 if (nallocated / 4 != size) /* overflow! */
4251 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004252 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004253 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004254 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004255 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004256 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004257
Tim Peters602f7402002-04-27 18:03:26 +00004258 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004259 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004260
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004261 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004262 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004263 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004264
Guido van Rossumd57fd912000-03-10 22:53:23 +00004265 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004266 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004267 *p++ = (char)(0xc0 | (ch >> 6));
4268 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004269 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004270 Py_ssize_t newpos;
4271 PyObject *rep;
4272 Py_ssize_t repsize, k, startpos;
4273 startpos = i-1;
4274#if SIZEOF_WCHAR_T == 2
4275 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004276#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004277 rep = unicode_encode_call_errorhandler(
4278 errors, &errorHandler, "utf-8", "surrogates not allowed",
4279 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4280 &exc, startpos, startpos+1, &newpos);
4281 if (!rep)
4282 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004283
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004284 if (PyBytes_Check(rep))
4285 repsize = PyBytes_GET_SIZE(rep);
4286 else
4287 repsize = PyUnicode_GET_SIZE(rep);
4288
4289 if (repsize > 4) {
4290 Py_ssize_t offset;
4291
4292 if (result == NULL)
4293 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004294 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004295 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004297 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4298 /* integer overflow */
4299 PyErr_NoMemory();
4300 goto error;
4301 }
4302 nallocated += repsize - 4;
4303 if (result != NULL) {
4304 if (_PyBytes_Resize(&result, nallocated) < 0)
4305 goto error;
4306 } else {
4307 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004308 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004309 goto error;
4310 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4311 }
4312 p = PyBytes_AS_STRING(result) + offset;
4313 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004315 if (PyBytes_Check(rep)) {
4316 char *prep = PyBytes_AS_STRING(rep);
4317 for(k = repsize; k > 0; k--)
4318 *p++ = *prep++;
4319 } else /* rep is unicode */ {
4320 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4321 Py_UNICODE c;
4322
4323 for(k=0; k<repsize; k++) {
4324 c = prep[k];
4325 if (0x80 <= c) {
4326 raise_encode_exception(&exc, "utf-8",
4327 PyUnicode_AS_UNICODE(unicode),
4328 size, i-1, i,
4329 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004330 goto error;
4331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004333 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004334 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004336 } else if (ch < 0x10000) {
4337 *p++ = (char)(0xe0 | (ch >> 12));
4338 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4339 *p++ = (char)(0x80 | (ch & 0x3f));
4340 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004341 /* Encode UCS4 Unicode ordinals */
4342 *p++ = (char)(0xf0 | (ch >> 18));
4343 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4344 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4345 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004346#if SIZEOF_WCHAR_T == 2
4347 wchar_offset++;
4348#endif
Tim Peters602f7402002-04-27 18:03:26 +00004349 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004350 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004351
Guido van Rossum98297ee2007-11-06 21:34:58 +00004352 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004353 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004354 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004355 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004356 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004357 }
4358 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004359 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004360 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004361 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004362 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004363 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004364
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004365 Py_XDECREF(errorHandler);
4366 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004367 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004368 error:
4369 Py_XDECREF(errorHandler);
4370 Py_XDECREF(exc);
4371 Py_XDECREF(result);
4372 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004373
Tim Peters602f7402002-04-27 18:03:26 +00004374#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004375}
4376
Alexander Belopolsky40018472011-02-26 01:02:56 +00004377PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4379 Py_ssize_t size,
4380 const char *errors)
4381{
4382 PyObject *v, *unicode;
4383
4384 unicode = PyUnicode_FromUnicode(s, size);
4385 if (unicode == NULL)
4386 return NULL;
4387 v = _PyUnicode_AsUTF8String(unicode, errors);
4388 Py_DECREF(unicode);
4389 return v;
4390}
4391
4392PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004393PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004395 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004396}
4397
Walter Dörwald41980ca2007-08-16 21:55:45 +00004398/* --- UTF-32 Codec ------------------------------------------------------- */
4399
4400PyObject *
4401PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 Py_ssize_t size,
4403 const char *errors,
4404 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004405{
4406 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4407}
4408
4409PyObject *
4410PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004411 Py_ssize_t size,
4412 const char *errors,
4413 int *byteorder,
4414 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004415{
4416 const char *starts = s;
4417 Py_ssize_t startinpos;
4418 Py_ssize_t endinpos;
4419 Py_ssize_t outpos;
4420 PyUnicodeObject *unicode;
4421 Py_UNICODE *p;
4422#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004423 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004424 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004425#else
4426 const int pairs = 0;
4427#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004428 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004429 int bo = 0; /* assume native ordering by default */
4430 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004431 /* Offsets from q for retrieving bytes in the right order. */
4432#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4433 int iorder[] = {0, 1, 2, 3};
4434#else
4435 int iorder[] = {3, 2, 1, 0};
4436#endif
4437 PyObject *errorHandler = NULL;
4438 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004439
Walter Dörwald41980ca2007-08-16 21:55:45 +00004440 q = (unsigned char *)s;
4441 e = q + size;
4442
4443 if (byteorder)
4444 bo = *byteorder;
4445
4446 /* Check for BOM marks (U+FEFF) in the input and adjust current
4447 byte order setting accordingly. In native mode, the leading BOM
4448 mark is skipped, in all other modes, it is copied to the output
4449 stream as-is (giving a ZWNBSP character). */
4450 if (bo == 0) {
4451 if (size >= 4) {
4452 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004453 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004454#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 if (bom == 0x0000FEFF) {
4456 q += 4;
4457 bo = -1;
4458 }
4459 else if (bom == 0xFFFE0000) {
4460 q += 4;
4461 bo = 1;
4462 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004463#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004464 if (bom == 0x0000FEFF) {
4465 q += 4;
4466 bo = 1;
4467 }
4468 else if (bom == 0xFFFE0000) {
4469 q += 4;
4470 bo = -1;
4471 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004472#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004473 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004474 }
4475
4476 if (bo == -1) {
4477 /* force LE */
4478 iorder[0] = 0;
4479 iorder[1] = 1;
4480 iorder[2] = 2;
4481 iorder[3] = 3;
4482 }
4483 else if (bo == 1) {
4484 /* force BE */
4485 iorder[0] = 3;
4486 iorder[1] = 2;
4487 iorder[2] = 1;
4488 iorder[3] = 0;
4489 }
4490
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004491 /* On narrow builds we split characters outside the BMP into two
4492 codepoints => count how much extra space we need. */
4493#ifndef Py_UNICODE_WIDE
4494 for (qq = q; qq < e; qq += 4)
4495 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4496 pairs++;
4497#endif
4498
4499 /* This might be one to much, because of a BOM */
4500 unicode = _PyUnicode_New((size+3)/4+pairs);
4501 if (!unicode)
4502 return NULL;
4503 if (size == 0)
4504 return (PyObject *)unicode;
4505
4506 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004508
Walter Dörwald41980ca2007-08-16 21:55:45 +00004509 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 Py_UCS4 ch;
4511 /* remaining bytes at the end? (size should be divisible by 4) */
4512 if (e-q<4) {
4513 if (consumed)
4514 break;
4515 errmsg = "truncated data";
4516 startinpos = ((const char *)q)-starts;
4517 endinpos = ((const char *)e)-starts;
4518 goto utf32Error;
4519 /* The remaining input chars are ignored if the callback
4520 chooses to skip the input */
4521 }
4522 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4523 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004524
Benjamin Peterson29060642009-01-31 22:14:21 +00004525 if (ch >= 0x110000)
4526 {
4527 errmsg = "codepoint not in range(0x110000)";
4528 startinpos = ((const char *)q)-starts;
4529 endinpos = startinpos+4;
4530 goto utf32Error;
4531 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004532#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004533 if (ch >= 0x10000)
4534 {
4535 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4536 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4537 }
4538 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004539#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004540 *p++ = ch;
4541 q += 4;
4542 continue;
4543 utf32Error:
4544 outpos = p-PyUnicode_AS_UNICODE(unicode);
4545 if (unicode_decode_call_errorhandler(
4546 errors, &errorHandler,
4547 "utf32", errmsg,
4548 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4549 &unicode, &outpos, &p))
4550 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004551 }
4552
4553 if (byteorder)
4554 *byteorder = bo;
4555
4556 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004557 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004558
4559 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004560 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004561 goto onError;
4562
4563 Py_XDECREF(errorHandler);
4564 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004565 if (PyUnicode_READY(unicode) == -1) {
4566 Py_DECREF(unicode);
4567 return NULL;
4568 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004569 return (PyObject *)unicode;
4570
Benjamin Peterson29060642009-01-31 22:14:21 +00004571 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004572 Py_DECREF(unicode);
4573 Py_XDECREF(errorHandler);
4574 Py_XDECREF(exc);
4575 return NULL;
4576}
4577
4578PyObject *
4579PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004580 Py_ssize_t size,
4581 const char *errors,
4582 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004583{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004584 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004585 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004586 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004587#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004588 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004589#else
4590 const int pairs = 0;
4591#endif
4592 /* Offsets from p for storing byte pairs in the right order. */
4593#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4594 int iorder[] = {0, 1, 2, 3};
4595#else
4596 int iorder[] = {3, 2, 1, 0};
4597#endif
4598
Benjamin Peterson29060642009-01-31 22:14:21 +00004599#define STORECHAR(CH) \
4600 do { \
4601 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4602 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4603 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4604 p[iorder[0]] = (CH) & 0xff; \
4605 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004606 } while(0)
4607
4608 /* In narrow builds we can output surrogate pairs as one codepoint,
4609 so we need less space. */
4610#ifndef Py_UNICODE_WIDE
4611 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004612 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
4613 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
4614 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004615#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004616 nsize = (size - pairs + (byteorder == 0));
4617 bytesize = nsize * 4;
4618 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004619 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004620 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004621 if (v == NULL)
4622 return NULL;
4623
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004624 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004625 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004626 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004627 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004628 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004629
4630 if (byteorder == -1) {
4631 /* force LE */
4632 iorder[0] = 0;
4633 iorder[1] = 1;
4634 iorder[2] = 2;
4635 iorder[3] = 3;
4636 }
4637 else if (byteorder == 1) {
4638 /* force BE */
4639 iorder[0] = 3;
4640 iorder[1] = 2;
4641 iorder[2] = 1;
4642 iorder[3] = 0;
4643 }
4644
4645 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004646 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004647#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004648 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
4649 Py_UCS4 ch2 = *s;
4650 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
4651 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
4652 s++;
4653 size--;
4654 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004655 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004656#endif
4657 STORECHAR(ch);
4658 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004659
4660 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004661 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004662#undef STORECHAR
4663}
4664
Alexander Belopolsky40018472011-02-26 01:02:56 +00004665PyObject *
4666PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004667{
4668 if (!PyUnicode_Check(unicode)) {
4669 PyErr_BadArgument();
4670 return NULL;
4671 }
4672 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004673 PyUnicode_GET_SIZE(unicode),
4674 NULL,
4675 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004676}
4677
Guido van Rossumd57fd912000-03-10 22:53:23 +00004678/* --- UTF-16 Codec ------------------------------------------------------- */
4679
Tim Peters772747b2001-08-09 22:21:55 +00004680PyObject *
4681PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004682 Py_ssize_t size,
4683 const char *errors,
4684 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004685{
Walter Dörwald69652032004-09-07 20:24:22 +00004686 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
4687}
4688
Antoine Pitrouab868312009-01-10 15:40:25 +00004689/* Two masks for fast checking of whether a C 'long' may contain
4690 UTF16-encoded surrogate characters. This is an efficient heuristic,
4691 assuming that non-surrogate characters with a code point >= 0x8000 are
4692 rare in most input.
4693 FAST_CHAR_MASK is used when the input is in native byte ordering,
4694 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00004695*/
Antoine Pitrouab868312009-01-10 15:40:25 +00004696#if (SIZEOF_LONG == 8)
4697# define FAST_CHAR_MASK 0x8000800080008000L
4698# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
4699#elif (SIZEOF_LONG == 4)
4700# define FAST_CHAR_MASK 0x80008000L
4701# define SWAPPED_FAST_CHAR_MASK 0x00800080L
4702#else
4703# error C 'long' size should be either 4 or 8!
4704#endif
4705
Walter Dörwald69652032004-09-07 20:24:22 +00004706PyObject *
4707PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004708 Py_ssize_t size,
4709 const char *errors,
4710 int *byteorder,
4711 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004712{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004713 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004714 Py_ssize_t startinpos;
4715 Py_ssize_t endinpos;
4716 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004717 PyUnicodeObject *unicode;
4718 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004719 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00004720 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00004721 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004722 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00004723 /* Offsets from q for retrieving byte pairs in the right order. */
4724#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4725 int ihi = 1, ilo = 0;
4726#else
4727 int ihi = 0, ilo = 1;
4728#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004729 PyObject *errorHandler = NULL;
4730 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004731
4732 /* Note: size will always be longer than the resulting Unicode
4733 character count */
4734 unicode = _PyUnicode_New(size);
4735 if (!unicode)
4736 return NULL;
4737 if (size == 0)
4738 return (PyObject *)unicode;
4739
4740 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004741 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00004742 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00004743 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004744
4745 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00004746 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004747
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004748 /* Check for BOM marks (U+FEFF) in the input and adjust current
4749 byte order setting accordingly. In native mode, the leading BOM
4750 mark is skipped, in all other modes, it is copied to the output
4751 stream as-is (giving a ZWNBSP character). */
4752 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00004753 if (size >= 2) {
4754 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004755#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004756 if (bom == 0xFEFF) {
4757 q += 2;
4758 bo = -1;
4759 }
4760 else if (bom == 0xFFFE) {
4761 q += 2;
4762 bo = 1;
4763 }
Tim Petersced69f82003-09-16 20:30:58 +00004764#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004765 if (bom == 0xFEFF) {
4766 q += 2;
4767 bo = 1;
4768 }
4769 else if (bom == 0xFFFE) {
4770 q += 2;
4771 bo = -1;
4772 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004773#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004775 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004776
Tim Peters772747b2001-08-09 22:21:55 +00004777 if (bo == -1) {
4778 /* force LE */
4779 ihi = 1;
4780 ilo = 0;
4781 }
4782 else if (bo == 1) {
4783 /* force BE */
4784 ihi = 0;
4785 ilo = 1;
4786 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004787#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4788 native_ordering = ilo < ihi;
4789#else
4790 native_ordering = ilo > ihi;
4791#endif
Tim Peters772747b2001-08-09 22:21:55 +00004792
Antoine Pitrouab868312009-01-10 15:40:25 +00004793 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00004794 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004795 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00004796 /* First check for possible aligned read of a C 'long'. Unaligned
4797 reads are more expensive, better to defer to another iteration. */
4798 if (!((size_t) q & LONG_PTR_MASK)) {
4799 /* Fast path for runs of non-surrogate chars. */
4800 register const unsigned char *_q = q;
4801 Py_UNICODE *_p = p;
4802 if (native_ordering) {
4803 /* Native ordering is simple: as long as the input cannot
4804 possibly contain a surrogate char, do an unrolled copy
4805 of several 16-bit code points to the target object.
4806 The non-surrogate check is done on several input bytes
4807 at a time (as many as a C 'long' can contain). */
4808 while (_q < aligned_end) {
4809 unsigned long data = * (unsigned long *) _q;
4810 if (data & FAST_CHAR_MASK)
4811 break;
4812 _p[0] = ((unsigned short *) _q)[0];
4813 _p[1] = ((unsigned short *) _q)[1];
4814#if (SIZEOF_LONG == 8)
4815 _p[2] = ((unsigned short *) _q)[2];
4816 _p[3] = ((unsigned short *) _q)[3];
4817#endif
4818 _q += SIZEOF_LONG;
4819 _p += SIZEOF_LONG / 2;
4820 }
4821 }
4822 else {
4823 /* Byteswapped ordering is similar, but we must decompose
4824 the copy bytewise, and take care of zero'ing out the
4825 upper bytes if the target object is in 32-bit units
4826 (that is, in UCS-4 builds). */
4827 while (_q < aligned_end) {
4828 unsigned long data = * (unsigned long *) _q;
4829 if (data & SWAPPED_FAST_CHAR_MASK)
4830 break;
4831 /* Zero upper bytes in UCS-4 builds */
4832#if (Py_UNICODE_SIZE > 2)
4833 _p[0] = 0;
4834 _p[1] = 0;
4835#if (SIZEOF_LONG == 8)
4836 _p[2] = 0;
4837 _p[3] = 0;
4838#endif
4839#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004840 /* Issue #4916; UCS-4 builds on big endian machines must
4841 fill the two last bytes of each 4-byte unit. */
4842#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
4843# define OFF 2
4844#else
4845# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00004846#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004847 ((unsigned char *) _p)[OFF + 1] = _q[0];
4848 ((unsigned char *) _p)[OFF + 0] = _q[1];
4849 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
4850 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
4851#if (SIZEOF_LONG == 8)
4852 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
4853 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
4854 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
4855 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
4856#endif
4857#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00004858 _q += SIZEOF_LONG;
4859 _p += SIZEOF_LONG / 2;
4860 }
4861 }
4862 p = _p;
4863 q = _q;
4864 if (q >= e)
4865 break;
4866 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004867 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004868
Benjamin Peterson14339b62009-01-31 16:36:08 +00004869 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00004870
4871 if (ch < 0xD800 || ch > 0xDFFF) {
4872 *p++ = ch;
4873 continue;
4874 }
4875
4876 /* UTF-16 code pair: */
4877 if (q > e) {
4878 errmsg = "unexpected end of data";
4879 startinpos = (((const char *)q) - 2) - starts;
4880 endinpos = ((const char *)e) + 1 - starts;
4881 goto utf16Error;
4882 }
4883 if (0xD800 <= ch && ch <= 0xDBFF) {
4884 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
4885 q += 2;
4886 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00004887#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004888 *p++ = ch;
4889 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004890#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004891 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004892#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004893 continue;
4894 }
4895 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004896 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00004897 startinpos = (((const char *)q)-4)-starts;
4898 endinpos = startinpos+2;
4899 goto utf16Error;
4900 }
4901
Benjamin Peterson14339b62009-01-31 16:36:08 +00004902 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004903 errmsg = "illegal encoding";
4904 startinpos = (((const char *)q)-2)-starts;
4905 endinpos = startinpos+2;
4906 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004907
Benjamin Peterson29060642009-01-31 22:14:21 +00004908 utf16Error:
4909 outpos = p - PyUnicode_AS_UNICODE(unicode);
4910 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00004911 errors,
4912 &errorHandler,
4913 "utf16", errmsg,
4914 &starts,
4915 (const char **)&e,
4916 &startinpos,
4917 &endinpos,
4918 &exc,
4919 (const char **)&q,
4920 &unicode,
4921 &outpos,
4922 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00004923 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004924 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004925 /* remaining byte at the end? (size should be even) */
4926 if (e == q) {
4927 if (!consumed) {
4928 errmsg = "truncated data";
4929 startinpos = ((const char *)q) - starts;
4930 endinpos = ((const char *)e) + 1 - starts;
4931 outpos = p - PyUnicode_AS_UNICODE(unicode);
4932 if (unicode_decode_call_errorhandler(
4933 errors,
4934 &errorHandler,
4935 "utf16", errmsg,
4936 &starts,
4937 (const char **)&e,
4938 &startinpos,
4939 &endinpos,
4940 &exc,
4941 (const char **)&q,
4942 &unicode,
4943 &outpos,
4944 &p))
4945 goto onError;
4946 /* The remaining input chars are ignored if the callback
4947 chooses to skip the input */
4948 }
4949 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004950
4951 if (byteorder)
4952 *byteorder = bo;
4953
Walter Dörwald69652032004-09-07 20:24:22 +00004954 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004955 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00004956
Guido van Rossumd57fd912000-03-10 22:53:23 +00004957 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004958 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004959 goto onError;
4960
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004961 Py_XDECREF(errorHandler);
4962 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004963 if (PyUnicode_READY(unicode) == -1) {
4964 Py_DECREF(unicode);
4965 return NULL;
4966 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004967 return (PyObject *)unicode;
4968
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004970 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004971 Py_XDECREF(errorHandler);
4972 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004973 return NULL;
4974}
4975
Antoine Pitrouab868312009-01-10 15:40:25 +00004976#undef FAST_CHAR_MASK
4977#undef SWAPPED_FAST_CHAR_MASK
4978
Tim Peters772747b2001-08-09 22:21:55 +00004979PyObject *
4980PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004981 Py_ssize_t size,
4982 const char *errors,
4983 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004984{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004985 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00004986 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004987 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004988#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004989 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00004990#else
4991 const int pairs = 0;
4992#endif
Tim Peters772747b2001-08-09 22:21:55 +00004993 /* Offsets from p for storing byte pairs in the right order. */
4994#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4995 int ihi = 1, ilo = 0;
4996#else
4997 int ihi = 0, ilo = 1;
4998#endif
4999
Benjamin Peterson29060642009-01-31 22:14:21 +00005000#define STORECHAR(CH) \
5001 do { \
5002 p[ihi] = ((CH) >> 8) & 0xff; \
5003 p[ilo] = (CH) & 0xff; \
5004 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005005 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005006
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005007#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005008 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005009 if (s[i] >= 0x10000)
5010 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005011#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005012 /* 2 * (size + pairs + (byteorder == 0)) */
5013 if (size > PY_SSIZE_T_MAX ||
5014 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005015 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005016 nsize = size + pairs + (byteorder == 0);
5017 bytesize = nsize * 2;
5018 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005019 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005020 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005021 if (v == NULL)
5022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005023
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005024 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005025 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005027 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005028 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005029
5030 if (byteorder == -1) {
5031 /* force LE */
5032 ihi = 1;
5033 ilo = 0;
5034 }
5035 else if (byteorder == 1) {
5036 /* force BE */
5037 ihi = 0;
5038 ilo = 1;
5039 }
5040
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005041 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 Py_UNICODE ch = *s++;
5043 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005044#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 if (ch >= 0x10000) {
5046 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5047 ch = 0xD800 | ((ch-0x10000) >> 10);
5048 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005049#endif
Tim Peters772747b2001-08-09 22:21:55 +00005050 STORECHAR(ch);
5051 if (ch2)
5052 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005053 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005054
5055 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005056 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005057#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005058}
5059
Alexander Belopolsky40018472011-02-26 01:02:56 +00005060PyObject *
5061PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005062{
5063 if (!PyUnicode_Check(unicode)) {
5064 PyErr_BadArgument();
5065 return NULL;
5066 }
5067 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005068 PyUnicode_GET_SIZE(unicode),
5069 NULL,
5070 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005071}
5072
5073/* --- Unicode Escape Codec ----------------------------------------------- */
5074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005075/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5076 if all the escapes in the string make it still a valid ASCII string.
5077 Returns -1 if any escapes were found which cause the string to
5078 pop out of ASCII range. Otherwise returns the length of the
5079 required buffer to hold the string.
5080 */
5081Py_ssize_t
5082length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5083{
5084 const unsigned char *p = (const unsigned char *)s;
5085 const unsigned char *end = p + size;
5086 Py_ssize_t length = 0;
5087
5088 if (size < 0)
5089 return -1;
5090
5091 for (; p < end; ++p) {
5092 if (*p > 127) {
5093 /* Non-ASCII */
5094 return -1;
5095 }
5096 else if (*p != '\\') {
5097 /* Normal character */
5098 ++length;
5099 }
5100 else {
5101 /* Backslash-escape, check next char */
5102 ++p;
5103 /* Escape sequence reaches till end of string or
5104 non-ASCII follow-up. */
5105 if (p >= end || *p > 127)
5106 return -1;
5107 switch (*p) {
5108 case '\n':
5109 /* backslash + \n result in zero characters */
5110 break;
5111 case '\\': case '\'': case '\"':
5112 case 'b': case 'f': case 't':
5113 case 'n': case 'r': case 'v': case 'a':
5114 ++length;
5115 break;
5116 case '0': case '1': case '2': case '3':
5117 case '4': case '5': case '6': case '7':
5118 case 'x': case 'u': case 'U': case 'N':
5119 /* these do not guarantee ASCII characters */
5120 return -1;
5121 default:
5122 /* count the backslash + the other character */
5123 length += 2;
5124 }
5125 }
5126 }
5127 return length;
5128}
5129
5130/* Similar to PyUnicode_WRITE but either write into wstr field
5131 or treat string as ASCII. */
5132#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5133 do { \
5134 if ((kind) != PyUnicode_WCHAR_KIND) \
5135 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5136 else \
5137 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5138 } while (0)
5139
5140#define WRITE_WSTR(buf, index, value) \
5141 assert(kind == PyUnicode_WCHAR_KIND), \
5142 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5143
5144
Fredrik Lundh06d12682001-01-24 07:59:11 +00005145static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005146
Alexander Belopolsky40018472011-02-26 01:02:56 +00005147PyObject *
5148PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005149 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005150 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005151{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005152 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005153 Py_ssize_t startinpos;
5154 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005155 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005156 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005157 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005158 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005159 char* message;
5160 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005161 PyObject *errorHandler = NULL;
5162 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005163 Py_ssize_t ascii_length;
5164 Py_ssize_t i;
5165 int kind;
5166 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005168 ascii_length = length_of_escaped_ascii_string(s, size);
5169
5170 /* After length_of_escaped_ascii_string() there are two alternatives,
5171 either the string is pure ASCII with named escapes like \n, etc.
5172 and we determined it's exact size (common case)
5173 or it contains \x, \u, ... escape sequences. then we create a
5174 legacy wchar string and resize it at the end of this function. */
5175 if (ascii_length >= 0) {
5176 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5177 if (!v)
5178 goto onError;
5179 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5180 kind = PyUnicode_1BYTE_KIND;
5181 data = PyUnicode_DATA(v);
5182 }
5183 else {
5184 /* Escaped strings will always be longer than the resulting
5185 Unicode string, so we start with size here and then reduce the
5186 length after conversion to the true value.
5187 (but if the error callback returns a long replacement string
5188 we'll have to allocate more space) */
5189 v = _PyUnicode_New(size);
5190 if (!v)
5191 goto onError;
5192 kind = PyUnicode_WCHAR_KIND;
5193 data = PyUnicode_AS_UNICODE(v);
5194 }
5195
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196 if (size == 0)
5197 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005198 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005200
Guido van Rossumd57fd912000-03-10 22:53:23 +00005201 while (s < end) {
5202 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005203 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005204 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005205
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005206 if (kind == PyUnicode_WCHAR_KIND) {
5207 assert(i < _PyUnicode_WSTR_LENGTH(v));
5208 }
5209 else {
5210 /* The only case in which i == ascii_length is a backslash
5211 followed by a newline. */
5212 assert(i <= ascii_length);
5213 }
5214
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215 /* Non-escape characters are interpreted as Unicode ordinals */
5216 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005217 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218 continue;
5219 }
5220
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005221 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222 /* \ - Escapes */
5223 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005224 c = *s++;
5225 if (s > end)
5226 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005227
5228 if (kind == PyUnicode_WCHAR_KIND) {
5229 assert(i < _PyUnicode_WSTR_LENGTH(v));
5230 }
5231 else {
5232 /* The only case in which i == ascii_length is a backslash
5233 followed by a newline. */
5234 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5235 }
5236
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005237 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005238
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005240 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005241 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5242 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5243 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5244 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5245 /* FF */
5246 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5247 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5248 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5249 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5250 /* VT */
5251 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5252 /* BEL, not classic C */
5253 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005254
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005256 case '0': case '1': case '2': case '3':
5257 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005258 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005259 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005260 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005261 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005262 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005264 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005265 break;
5266
Benjamin Peterson29060642009-01-31 22:14:21 +00005267 /* hex escapes */
5268 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005269 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005270 digits = 2;
5271 message = "truncated \\xXX escape";
5272 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005273
Benjamin Peterson29060642009-01-31 22:14:21 +00005274 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005275 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005276 digits = 4;
5277 message = "truncated \\uXXXX escape";
5278 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005279
Benjamin Peterson29060642009-01-31 22:14:21 +00005280 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005281 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005282 digits = 8;
5283 message = "truncated \\UXXXXXXXX escape";
5284 hexescape:
5285 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005286 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005287 if (s+digits>end) {
5288 endinpos = size;
5289 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005290 errors, &errorHandler,
5291 "unicodeescape", "end of string in escape sequence",
5292 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005293 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005294 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005295 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005296 goto nextByte;
5297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005298 for (j = 0; j < digits; ++j) {
5299 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005300 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005301 endinpos = (s+j+1)-starts;
5302 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005303 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 errors, &errorHandler,
5305 "unicodeescape", message,
5306 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005307 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005308 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005309 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005310 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005311 }
5312 chr = (chr<<4) & ~0xF;
5313 if (c >= '0' && c <= '9')
5314 chr += c - '0';
5315 else if (c >= 'a' && c <= 'f')
5316 chr += 10 + c - 'a';
5317 else
5318 chr += 10 + c - 'A';
5319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005320 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005321 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005322 /* _decoding_error will have already written into the
5323 target buffer. */
5324 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005325 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005326 /* when we get here, chr is a 32-bit unicode character */
5327 if (chr <= 0xffff)
5328 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005329 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005330 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005331 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005332 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005333#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005334 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005335#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005336 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005337 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5338 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005339#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005340 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005341 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005342 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005343 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005344 errors, &errorHandler,
5345 "unicodeescape", "illegal Unicode character",
5346 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005347 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005348 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005349 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005350 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005351 break;
5352
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005354 case 'N':
5355 message = "malformed \\N character escape";
5356 if (ucnhash_CAPI == NULL) {
5357 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005358 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5359 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005360 if (ucnhash_CAPI == NULL)
5361 goto ucnhashError;
5362 }
5363 if (*s == '{') {
5364 const char *start = s+1;
5365 /* look for the closing brace */
5366 while (*s != '}' && s < end)
5367 s++;
5368 if (s > start && s < end && *s == '}') {
5369 /* found a name. look it up in the unicode database */
5370 message = "unknown Unicode character name";
5371 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005372 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5373 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005374 goto store;
5375 }
5376 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005377 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005378 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 errors, &errorHandler,
5381 "unicodeescape", message,
5382 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005383 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005384 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005385 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005386 break;
5387
5388 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005389 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005390 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005391 message = "\\ at end of string";
5392 s--;
5393 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005394 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005395 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005396 errors, &errorHandler,
5397 "unicodeescape", message,
5398 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005399 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005400 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005401 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005402 }
5403 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005404 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5405 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005406 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005407 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005410 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005412 /* Ensure the length prediction worked in case of ASCII strings */
5413 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5414
Victor Stinnerfe226c02011-10-03 03:52:20 +02005415 if (kind == PyUnicode_WCHAR_KIND)
5416 {
5417 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5418 goto onError;
5419 if (PyUnicode_READY(v) == -1)
5420 goto onError;
5421 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005422 Py_XDECREF(errorHandler);
5423 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005425
Benjamin Peterson29060642009-01-31 22:14:21 +00005426 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005427 PyErr_SetString(
5428 PyExc_UnicodeError,
5429 "\\N escapes not supported (can't load unicodedata module)"
5430 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005431 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005432 Py_XDECREF(errorHandler);
5433 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005434 return NULL;
5435
Benjamin Peterson29060642009-01-31 22:14:21 +00005436 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005438 Py_XDECREF(errorHandler);
5439 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005440 return NULL;
5441}
5442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005443#undef WRITE_ASCII_OR_WSTR
5444#undef WRITE_WSTR
5445
Guido van Rossumd57fd912000-03-10 22:53:23 +00005446/* Return a Unicode-Escape string version of the Unicode object.
5447
5448 If quotes is true, the string is enclosed in u"" or u'' quotes as
5449 appropriate.
5450
5451*/
5452
Walter Dörwald79e913e2007-05-12 11:08:06 +00005453static const char *hexdigits = "0123456789abcdef";
5454
Alexander Belopolsky40018472011-02-26 01:02:56 +00005455PyObject *
5456PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005457 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005459 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005461
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005462#ifdef Py_UNICODE_WIDE
5463 const Py_ssize_t expandsize = 10;
5464#else
5465 const Py_ssize_t expandsize = 6;
5466#endif
5467
Thomas Wouters89f507f2006-12-13 04:49:30 +00005468 /* XXX(nnorwitz): rather than over-allocating, it would be
5469 better to choose a different scheme. Perhaps scan the
5470 first N-chars of the string and allocate based on that size.
5471 */
5472 /* Initial allocation is based on the longest-possible unichr
5473 escape.
5474
5475 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5476 unichr, so in this case it's the longest unichr escape. In
5477 narrow (UTF-16) builds this is five chars per source unichr
5478 since there are two unichrs in the surrogate pair, so in narrow
5479 (UTF-16) builds it's not the longest unichr escape.
5480
5481 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5482 so in the narrow (UTF-16) build case it's the longest unichr
5483 escape.
5484 */
5485
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005486 if (size == 0)
5487 return PyBytes_FromStringAndSize(NULL, 0);
5488
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005489 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005490 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005491
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005492 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 2
5494 + expandsize*size
5495 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005496 if (repr == NULL)
5497 return NULL;
5498
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005499 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005500
Guido van Rossumd57fd912000-03-10 22:53:23 +00005501 while (size-- > 0) {
5502 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005503
Walter Dörwald79e913e2007-05-12 11:08:06 +00005504 /* Escape backslashes */
5505 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005506 *p++ = '\\';
5507 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005508 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005509 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005510
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005511#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005512 /* Map 21-bit characters to '\U00xxxxxx' */
5513 else if (ch >= 0x10000) {
5514 *p++ = '\\';
5515 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005516 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5517 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5518 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5519 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5520 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5521 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5522 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5523 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005524 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005525 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005526#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005527 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5528 else if (ch >= 0xD800 && ch < 0xDC00) {
5529 Py_UNICODE ch2;
5530 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005531
Benjamin Peterson29060642009-01-31 22:14:21 +00005532 ch2 = *s++;
5533 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005534 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005535 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5536 *p++ = '\\';
5537 *p++ = 'U';
5538 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5539 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5540 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5541 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5542 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5543 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5544 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5545 *p++ = hexdigits[ucs & 0x0000000F];
5546 continue;
5547 }
5548 /* Fall through: isolated surrogates are copied as-is */
5549 s--;
5550 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005551 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005552#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005553
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005555 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005556 *p++ = '\\';
5557 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005558 *p++ = hexdigits[(ch >> 12) & 0x000F];
5559 *p++ = hexdigits[(ch >> 8) & 0x000F];
5560 *p++ = hexdigits[(ch >> 4) & 0x000F];
5561 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005562 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005563
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005564 /* Map special whitespace to '\t', \n', '\r' */
5565 else if (ch == '\t') {
5566 *p++ = '\\';
5567 *p++ = 't';
5568 }
5569 else if (ch == '\n') {
5570 *p++ = '\\';
5571 *p++ = 'n';
5572 }
5573 else if (ch == '\r') {
5574 *p++ = '\\';
5575 *p++ = 'r';
5576 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005577
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005578 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005579 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005581 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005582 *p++ = hexdigits[(ch >> 4) & 0x000F];
5583 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005584 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005585
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586 /* Copy everything else as-is */
5587 else
5588 *p++ = (char) ch;
5589 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005591 assert(p - PyBytes_AS_STRING(repr) > 0);
5592 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5593 return NULL;
5594 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005595}
5596
Alexander Belopolsky40018472011-02-26 01:02:56 +00005597PyObject *
5598PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005600 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601 if (!PyUnicode_Check(unicode)) {
5602 PyErr_BadArgument();
5603 return NULL;
5604 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005605 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5606 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005607 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005608}
5609
5610/* --- Raw Unicode Escape Codec ------------------------------------------- */
5611
Alexander Belopolsky40018472011-02-26 01:02:56 +00005612PyObject *
5613PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005614 Py_ssize_t size,
5615 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005616{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005617 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005618 Py_ssize_t startinpos;
5619 Py_ssize_t endinpos;
5620 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005622 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623 const char *end;
5624 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 PyObject *errorHandler = NULL;
5626 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005627
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628 /* Escaped strings will always be longer than the resulting
5629 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005630 length after conversion to the true value. (But decoding error
5631 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 v = _PyUnicode_New(size);
5633 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005634 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005636 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005637 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005638 end = s + size;
5639 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005640 unsigned char c;
5641 Py_UCS4 x;
5642 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005643 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644
Benjamin Peterson29060642009-01-31 22:14:21 +00005645 /* Non-escape characters are interpreted as Unicode ordinals */
5646 if (*s != '\\') {
5647 *p++ = (unsigned char)*s++;
5648 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005649 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005650 startinpos = s-starts;
5651
5652 /* \u-escapes are only interpreted iff the number of leading
5653 backslashes if odd */
5654 bs = s;
5655 for (;s < end;) {
5656 if (*s != '\\')
5657 break;
5658 *p++ = (unsigned char)*s++;
5659 }
5660 if (((s - bs) & 1) == 0 ||
5661 s >= end ||
5662 (*s != 'u' && *s != 'U')) {
5663 continue;
5664 }
5665 p--;
5666 count = *s=='u' ? 4 : 8;
5667 s++;
5668
5669 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
5670 outpos = p-PyUnicode_AS_UNICODE(v);
5671 for (x = 0, i = 0; i < count; ++i, ++s) {
5672 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005673 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 endinpos = s-starts;
5675 if (unicode_decode_call_errorhandler(
5676 errors, &errorHandler,
5677 "rawunicodeescape", "truncated \\uXXXX",
5678 &starts, &end, &startinpos, &endinpos, &exc, &s,
5679 &v, &outpos, &p))
5680 goto onError;
5681 goto nextByte;
5682 }
5683 x = (x<<4) & ~0xF;
5684 if (c >= '0' && c <= '9')
5685 x += c - '0';
5686 else if (c >= 'a' && c <= 'f')
5687 x += 10 + c - 'a';
5688 else
5689 x += 10 + c - 'A';
5690 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00005691 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 /* UCS-2 character */
5693 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005694 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005695 /* UCS-4 character. Either store directly, or as
5696 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00005697#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005698 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005699#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005700 x -= 0x10000L;
5701 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
5702 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00005703#endif
5704 } else {
5705 endinpos = s-starts;
5706 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005707 if (unicode_decode_call_errorhandler(
5708 errors, &errorHandler,
5709 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005710 &starts, &end, &startinpos, &endinpos, &exc, &s,
5711 &v, &outpos, &p))
5712 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005713 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 nextByte:
5715 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02005717 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005719 Py_XDECREF(errorHandler);
5720 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005721 if (PyUnicode_READY(v) == -1) {
5722 Py_DECREF(v);
5723 return NULL;
5724 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005729 Py_XDECREF(errorHandler);
5730 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 return NULL;
5732}
5733
Alexander Belopolsky40018472011-02-26 01:02:56 +00005734PyObject *
5735PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005736 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005738 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 char *p;
5740 char *q;
5741
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005742#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005743 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005744#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005745 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005746#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00005747
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005748 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005749 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005750
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005751 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752 if (repr == NULL)
5753 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005754 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005755 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005757 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758 while (size-- > 0) {
5759 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005760#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005761 /* Map 32-bit characters to '\Uxxxxxxxx' */
5762 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005763 *p++ = '\\';
5764 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005765 *p++ = hexdigits[(ch >> 28) & 0xf];
5766 *p++ = hexdigits[(ch >> 24) & 0xf];
5767 *p++ = hexdigits[(ch >> 20) & 0xf];
5768 *p++ = hexdigits[(ch >> 16) & 0xf];
5769 *p++ = hexdigits[(ch >> 12) & 0xf];
5770 *p++ = hexdigits[(ch >> 8) & 0xf];
5771 *p++ = hexdigits[(ch >> 4) & 0xf];
5772 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005773 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005774 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00005775#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5777 if (ch >= 0xD800 && ch < 0xDC00) {
5778 Py_UNICODE ch2;
5779 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005780
Benjamin Peterson29060642009-01-31 22:14:21 +00005781 ch2 = *s++;
5782 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005783 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005784 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5785 *p++ = '\\';
5786 *p++ = 'U';
5787 *p++ = hexdigits[(ucs >> 28) & 0xf];
5788 *p++ = hexdigits[(ucs >> 24) & 0xf];
5789 *p++ = hexdigits[(ucs >> 20) & 0xf];
5790 *p++ = hexdigits[(ucs >> 16) & 0xf];
5791 *p++ = hexdigits[(ucs >> 12) & 0xf];
5792 *p++ = hexdigits[(ucs >> 8) & 0xf];
5793 *p++ = hexdigits[(ucs >> 4) & 0xf];
5794 *p++ = hexdigits[ucs & 0xf];
5795 continue;
5796 }
5797 /* Fall through: isolated surrogates are copied as-is */
5798 s--;
5799 size++;
5800 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005801#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005802 /* Map 16-bit characters to '\uxxxx' */
5803 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005804 *p++ = '\\';
5805 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005806 *p++ = hexdigits[(ch >> 12) & 0xf];
5807 *p++ = hexdigits[(ch >> 8) & 0xf];
5808 *p++ = hexdigits[(ch >> 4) & 0xf];
5809 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005810 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005811 /* Copy everything else as-is */
5812 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005813 *p++ = (char) ch;
5814 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005815 size = p - q;
5816
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005817 assert(size > 0);
5818 if (_PyBytes_Resize(&repr, size) < 0)
5819 return NULL;
5820 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005821}
5822
Alexander Belopolsky40018472011-02-26 01:02:56 +00005823PyObject *
5824PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005825{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005826 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005827 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00005828 PyErr_BadArgument();
5829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830 }
Walter Dörwald711005d2007-05-12 12:03:26 +00005831 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5832 PyUnicode_GET_SIZE(unicode));
5833
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005834 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005835}
5836
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005837/* --- Unicode Internal Codec ------------------------------------------- */
5838
Alexander Belopolsky40018472011-02-26 01:02:56 +00005839PyObject *
5840_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005841 Py_ssize_t size,
5842 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005843{
5844 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005845 Py_ssize_t startinpos;
5846 Py_ssize_t endinpos;
5847 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005848 PyUnicodeObject *v;
5849 Py_UNICODE *p;
5850 const char *end;
5851 const char *reason;
5852 PyObject *errorHandler = NULL;
5853 PyObject *exc = NULL;
5854
Neal Norwitzd43069c2006-01-08 01:12:10 +00005855#ifdef Py_UNICODE_WIDE
5856 Py_UNICODE unimax = PyUnicode_GetMax();
5857#endif
5858
Thomas Wouters89f507f2006-12-13 04:49:30 +00005859 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005860 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
5861 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005863 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
5864 as string was created with the old API. */
5865 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005867 p = PyUnicode_AS_UNICODE(v);
5868 end = s + size;
5869
5870 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00005871 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005872 /* We have to sanity check the raw data, otherwise doom looms for
5873 some malformed UCS-4 data. */
5874 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00005875#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005876 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00005877#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005878 end-s < Py_UNICODE_SIZE
5879 )
Benjamin Peterson29060642009-01-31 22:14:21 +00005880 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005881 startinpos = s - starts;
5882 if (end-s < Py_UNICODE_SIZE) {
5883 endinpos = end-starts;
5884 reason = "truncated input";
5885 }
5886 else {
5887 endinpos = s - starts + Py_UNICODE_SIZE;
5888 reason = "illegal code point (> 0x10FFFF)";
5889 }
5890 outpos = p - PyUnicode_AS_UNICODE(v);
5891 if (unicode_decode_call_errorhandler(
5892 errors, &errorHandler,
5893 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00005894 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00005895 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005896 goto onError;
5897 }
5898 }
5899 else {
5900 p++;
5901 s += Py_UNICODE_SIZE;
5902 }
5903 }
5904
Victor Stinnerfe226c02011-10-03 03:52:20 +02005905 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005906 goto onError;
5907 Py_XDECREF(errorHandler);
5908 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005909 if (PyUnicode_READY(v) == -1) {
5910 Py_DECREF(v);
5911 return NULL;
5912 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005913 return (PyObject *)v;
5914
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005916 Py_XDECREF(v);
5917 Py_XDECREF(errorHandler);
5918 Py_XDECREF(exc);
5919 return NULL;
5920}
5921
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922/* --- Latin-1 Codec ------------------------------------------------------ */
5923
Alexander Belopolsky40018472011-02-26 01:02:56 +00005924PyObject *
5925PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005926 Py_ssize_t size,
5927 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928{
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02005930 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931}
5932
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005933/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005934static void
5935make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005936 const char *encoding,
5937 const Py_UNICODE *unicode, Py_ssize_t size,
5938 Py_ssize_t startpos, Py_ssize_t endpos,
5939 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005940{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005941 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 *exceptionObject = PyUnicodeEncodeError_Create(
5943 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944 }
5945 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00005946 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
5947 goto onError;
5948 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
5949 goto onError;
5950 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
5951 goto onError;
5952 return;
5953 onError:
5954 Py_DECREF(*exceptionObject);
5955 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005956 }
5957}
5958
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005959/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005960static void
5961raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005962 const char *encoding,
5963 const Py_UNICODE *unicode, Py_ssize_t size,
5964 Py_ssize_t startpos, Py_ssize_t endpos,
5965 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005966{
5967 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005969 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005970 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005971}
5972
5973/* error handling callback helper:
5974 build arguments, call the callback and check the arguments,
5975 put the result into newpos and return the replacement string, which
5976 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00005977static PyObject *
5978unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005979 PyObject **errorHandler,
5980 const char *encoding, const char *reason,
5981 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
5982 Py_ssize_t startpos, Py_ssize_t endpos,
5983 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005984{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00005985 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005986
5987 PyObject *restuple;
5988 PyObject *resunicode;
5989
5990 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005991 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005992 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005994 }
5995
5996 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00005997 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005998 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006000
6001 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006003 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006005 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006006 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 Py_DECREF(restuple);
6008 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006009 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006010 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 &resunicode, newpos)) {
6012 Py_DECREF(restuple);
6013 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006014 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006015 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6016 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6017 Py_DECREF(restuple);
6018 return NULL;
6019 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006020 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006022 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6024 Py_DECREF(restuple);
6025 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006026 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006027 Py_INCREF(resunicode);
6028 Py_DECREF(restuple);
6029 return resunicode;
6030}
6031
Alexander Belopolsky40018472011-02-26 01:02:56 +00006032static PyObject *
6033unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006034 Py_ssize_t size,
6035 const char *errors,
6036 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006037{
6038 /* output object */
6039 PyObject *res;
6040 /* pointers to the beginning and end+1 of input */
6041 const Py_UNICODE *startp = p;
6042 const Py_UNICODE *endp = p + size;
6043 /* pointer to the beginning of the unencodable characters */
6044 /* const Py_UNICODE *badp = NULL; */
6045 /* pointer into the output */
6046 char *str;
6047 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006048 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006049 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6050 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006051 PyObject *errorHandler = NULL;
6052 PyObject *exc = NULL;
6053 /* the following variable is used for caching string comparisons
6054 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6055 int known_errorHandler = -1;
6056
6057 /* allocate enough for a simple encoding without
6058 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006059 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006060 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006061 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006062 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006063 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006064 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006065 ressize = size;
6066
6067 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006068 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006069
Benjamin Peterson29060642009-01-31 22:14:21 +00006070 /* can we encode this? */
6071 if (c<limit) {
6072 /* no overflow check, because we know that the space is enough */
6073 *str++ = (char)c;
6074 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006075 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 else {
6077 Py_ssize_t unicodepos = p-startp;
6078 Py_ssize_t requiredsize;
6079 PyObject *repunicode;
6080 Py_ssize_t repsize;
6081 Py_ssize_t newpos;
6082 Py_ssize_t respos;
6083 Py_UNICODE *uni2;
6084 /* startpos for collecting unencodable chars */
6085 const Py_UNICODE *collstart = p;
6086 const Py_UNICODE *collend = p;
6087 /* find all unecodable characters */
6088 while ((collend < endp) && ((*collend)>=limit))
6089 ++collend;
6090 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6091 if (known_errorHandler==-1) {
6092 if ((errors==NULL) || (!strcmp(errors, "strict")))
6093 known_errorHandler = 1;
6094 else if (!strcmp(errors, "replace"))
6095 known_errorHandler = 2;
6096 else if (!strcmp(errors, "ignore"))
6097 known_errorHandler = 3;
6098 else if (!strcmp(errors, "xmlcharrefreplace"))
6099 known_errorHandler = 4;
6100 else
6101 known_errorHandler = 0;
6102 }
6103 switch (known_errorHandler) {
6104 case 1: /* strict */
6105 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6106 goto onError;
6107 case 2: /* replace */
6108 while (collstart++<collend)
6109 *str++ = '?'; /* fall through */
6110 case 3: /* ignore */
6111 p = collend;
6112 break;
6113 case 4: /* xmlcharrefreplace */
6114 respos = str - PyBytes_AS_STRING(res);
6115 /* determine replacement size (temporarily (mis)uses p) */
6116 for (p = collstart, repsize = 0; p < collend; ++p) {
6117 if (*p<10)
6118 repsize += 2+1+1;
6119 else if (*p<100)
6120 repsize += 2+2+1;
6121 else if (*p<1000)
6122 repsize += 2+3+1;
6123 else if (*p<10000)
6124 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006125#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 else
6127 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006128#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006129 else if (*p<100000)
6130 repsize += 2+5+1;
6131 else if (*p<1000000)
6132 repsize += 2+6+1;
6133 else
6134 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006135#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006136 }
6137 requiredsize = respos+repsize+(endp-collend);
6138 if (requiredsize > ressize) {
6139 if (requiredsize<2*ressize)
6140 requiredsize = 2*ressize;
6141 if (_PyBytes_Resize(&res, requiredsize))
6142 goto onError;
6143 str = PyBytes_AS_STRING(res) + respos;
6144 ressize = requiredsize;
6145 }
6146 /* generate replacement (temporarily (mis)uses p) */
6147 for (p = collstart; p < collend; ++p) {
6148 str += sprintf(str, "&#%d;", (int)*p);
6149 }
6150 p = collend;
6151 break;
6152 default:
6153 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6154 encoding, reason, startp, size, &exc,
6155 collstart-startp, collend-startp, &newpos);
6156 if (repunicode == NULL)
6157 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006158 if (PyBytes_Check(repunicode)) {
6159 /* Directly copy bytes result to output. */
6160 repsize = PyBytes_Size(repunicode);
6161 if (repsize > 1) {
6162 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006163 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006164 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6165 Py_DECREF(repunicode);
6166 goto onError;
6167 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006168 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006169 ressize += repsize-1;
6170 }
6171 memcpy(str, PyBytes_AsString(repunicode), repsize);
6172 str += repsize;
6173 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006174 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006175 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006176 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006177 /* need more space? (at least enough for what we
6178 have+the replacement+the rest of the string, so
6179 we won't have to check space for encodable characters) */
6180 respos = str - PyBytes_AS_STRING(res);
6181 repsize = PyUnicode_GET_SIZE(repunicode);
6182 requiredsize = respos+repsize+(endp-collend);
6183 if (requiredsize > ressize) {
6184 if (requiredsize<2*ressize)
6185 requiredsize = 2*ressize;
6186 if (_PyBytes_Resize(&res, requiredsize)) {
6187 Py_DECREF(repunicode);
6188 goto onError;
6189 }
6190 str = PyBytes_AS_STRING(res) + respos;
6191 ressize = requiredsize;
6192 }
6193 /* check if there is anything unencodable in the replacement
6194 and copy it to the output */
6195 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6196 c = *uni2;
6197 if (c >= limit) {
6198 raise_encode_exception(&exc, encoding, startp, size,
6199 unicodepos, unicodepos+1, reason);
6200 Py_DECREF(repunicode);
6201 goto onError;
6202 }
6203 *str = (char)c;
6204 }
6205 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006206 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006207 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006208 }
6209 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006210 /* Resize if we allocated to much */
6211 size = str - PyBytes_AS_STRING(res);
6212 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006213 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006214 if (_PyBytes_Resize(&res, size) < 0)
6215 goto onError;
6216 }
6217
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006218 Py_XDECREF(errorHandler);
6219 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006220 return res;
6221
6222 onError:
6223 Py_XDECREF(res);
6224 Py_XDECREF(errorHandler);
6225 Py_XDECREF(exc);
6226 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227}
6228
Alexander Belopolsky40018472011-02-26 01:02:56 +00006229PyObject *
6230PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006231 Py_ssize_t size,
6232 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006234 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235}
6236
Alexander Belopolsky40018472011-02-26 01:02:56 +00006237PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006238_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239{
6240 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006241 PyErr_BadArgument();
6242 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006244 if (PyUnicode_READY(unicode) == -1)
6245 return NULL;
6246 /* Fast path: if it is a one-byte string, construct
6247 bytes object directly. */
6248 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6249 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6250 PyUnicode_GET_LENGTH(unicode));
6251 /* Non-Latin-1 characters present. Defer to above function to
6252 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006253 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006254 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006255 errors);
6256}
6257
6258PyObject*
6259PyUnicode_AsLatin1String(PyObject *unicode)
6260{
6261 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006262}
6263
6264/* --- 7-bit ASCII Codec -------------------------------------------------- */
6265
Alexander Belopolsky40018472011-02-26 01:02:56 +00006266PyObject *
6267PyUnicode_DecodeASCII(const char *s,
6268 Py_ssize_t size,
6269 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006271 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006272 PyUnicodeObject *v;
6273 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006274 Py_ssize_t startinpos;
6275 Py_ssize_t endinpos;
6276 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006277 const char *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006278 unsigned char* d;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006279 PyObject *errorHandler = NULL;
6280 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006281 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00006282
Guido van Rossumd57fd912000-03-10 22:53:23 +00006283 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006284 if (size == 1 && *(unsigned char*)s < 128)
6285 return PyUnicode_FromOrdinal(*(unsigned char*)s);
6286
6287 /* Fast path. Assume the input actually *is* ASCII, and allocate
6288 a single-block Unicode object with that assumption. If there is
6289 an error, drop the object and start over. */
6290 v = (PyUnicodeObject*)PyUnicode_New(size, 127);
6291 if (v == NULL)
6292 goto onError;
6293 d = PyUnicode_1BYTE_DATA(v);
6294 for (i = 0; i < size; i++) {
6295 unsigned char ch = ((unsigned char*)s)[i];
6296 if (ch < 128)
6297 d[i] = ch;
6298 else
6299 break;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006300 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006301 if (i == size)
6302 return (PyObject*)v;
6303 Py_DECREF(v); /* start over */
Tim Petersced69f82003-09-16 20:30:58 +00006304
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 v = _PyUnicode_New(size);
6306 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006307 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006311 e = s + size;
6312 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 register unsigned char c = (unsigned char)*s;
6314 if (c < 128) {
6315 *p++ = c;
6316 ++s;
6317 }
6318 else {
6319 startinpos = s-starts;
6320 endinpos = startinpos + 1;
6321 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
6322 if (unicode_decode_call_errorhandler(
6323 errors, &errorHandler,
6324 "ascii", "ordinal not in range(128)",
6325 &starts, &e, &startinpos, &endinpos, &exc, &s,
6326 &v, &outpos, &p))
6327 goto onError;
6328 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00006330 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006331 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006332 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006333 Py_XDECREF(errorHandler);
6334 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006335 if (PyUnicode_READY(v) == -1) {
6336 Py_DECREF(v);
6337 return NULL;
6338 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006339 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006340
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006343 Py_XDECREF(errorHandler);
6344 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345 return NULL;
6346}
6347
Alexander Belopolsky40018472011-02-26 01:02:56 +00006348PyObject *
6349PyUnicode_EncodeASCII(const Py_UNICODE *p,
6350 Py_ssize_t size,
6351 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006352{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006353 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354}
6355
Alexander Belopolsky40018472011-02-26 01:02:56 +00006356PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006357_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006358{
6359 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 PyErr_BadArgument();
6361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006363 if (PyUnicode_READY(unicode) == -1)
6364 return NULL;
6365 /* Fast path: if it is an ASCII-only string, construct bytes object
6366 directly. Else defer to above function to raise the exception. */
6367 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6368 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6369 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006372 errors);
6373}
6374
6375PyObject *
6376PyUnicode_AsASCIIString(PyObject *unicode)
6377{
6378 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379}
6380
Victor Stinner99b95382011-07-04 14:23:54 +02006381#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006382
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006383/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006384
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006385#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006386#define NEED_RETRY
6387#endif
6388
6389/* XXX This code is limited to "true" double-byte encodings, as
6390 a) it assumes an incomplete character consists of a single byte, and
6391 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006393
Alexander Belopolsky40018472011-02-26 01:02:56 +00006394static int
6395is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006396{
6397 const char *curr = s + offset;
6398
6399 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 const char *prev = CharPrev(s, curr);
6401 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006402 }
6403 return 0;
6404}
6405
6406/*
6407 * Decode MBCS string into unicode object. If 'final' is set, converts
6408 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6409 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006410static int
6411decode_mbcs(PyUnicodeObject **v,
6412 const char *s, /* MBCS string */
6413 int size, /* sizeof MBCS string */
6414 int final,
6415 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006416{
6417 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006418 Py_ssize_t n;
6419 DWORD usize;
6420 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006421
6422 assert(size >= 0);
6423
Victor Stinner554f3f02010-06-16 23:33:54 +00006424 /* check and handle 'errors' arg */
6425 if (errors==NULL || strcmp(errors, "strict")==0)
6426 flags = MB_ERR_INVALID_CHARS;
6427 else if (strcmp(errors, "ignore")==0)
6428 flags = 0;
6429 else {
6430 PyErr_Format(PyExc_ValueError,
6431 "mbcs encoding does not support errors='%s'",
6432 errors);
6433 return -1;
6434 }
6435
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006436 /* Skip trailing lead-byte unless 'final' is set */
6437 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006439
6440 /* First get the size of the result */
6441 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006442 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6443 if (usize==0)
6444 goto mbcs_decode_error;
6445 } else
6446 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006447
6448 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006449 /* Create unicode object */
6450 *v = _PyUnicode_New(usize);
6451 if (*v == NULL)
6452 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006453 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006454 }
6455 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 /* Extend unicode object */
6457 n = PyUnicode_GET_SIZE(*v);
Victor Stinnerfe226c02011-10-03 03:52:20 +02006458 if (PyUnicode_Resize(v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006459 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006460 }
6461
6462 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006463 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006465 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6466 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006468 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006469 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006470
6471mbcs_decode_error:
6472 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6473 we raise a UnicodeDecodeError - else it is a 'generic'
6474 windows error
6475 */
6476 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6477 /* Ideally, we should get reason from FormatMessage - this
6478 is the Windows 2000 English version of the message
6479 */
6480 PyObject *exc = NULL;
6481 const char *reason = "No mapping for the Unicode character exists "
6482 "in the target multi-byte code page.";
6483 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6484 if (exc != NULL) {
6485 PyCodec_StrictErrors(exc);
6486 Py_DECREF(exc);
6487 }
6488 } else {
6489 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6490 }
6491 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006492}
6493
Alexander Belopolsky40018472011-02-26 01:02:56 +00006494PyObject *
6495PyUnicode_DecodeMBCSStateful(const char *s,
6496 Py_ssize_t size,
6497 const char *errors,
6498 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006499{
6500 PyUnicodeObject *v = NULL;
6501 int done;
6502
6503 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006505
6506#ifdef NEED_RETRY
6507 retry:
6508 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006509 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006510 else
6511#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006512 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006513
6514 if (done < 0) {
6515 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006517 }
6518
6519 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006521
6522#ifdef NEED_RETRY
6523 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 s += done;
6525 size -= done;
6526 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006527 }
6528#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006529 if (PyUnicode_READY(v) == -1) {
6530 Py_DECREF(v);
6531 return NULL;
6532 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006533 return (PyObject *)v;
6534}
6535
Alexander Belopolsky40018472011-02-26 01:02:56 +00006536PyObject *
6537PyUnicode_DecodeMBCS(const char *s,
6538 Py_ssize_t size,
6539 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006540{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006541 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6542}
6543
6544/*
6545 * Convert unicode into string object (MBCS).
6546 * Returns 0 if succeed, -1 otherwise.
6547 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006548static int
6549encode_mbcs(PyObject **repr,
6550 const Py_UNICODE *p, /* unicode */
6551 int size, /* size of unicode */
6552 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006553{
Victor Stinner554f3f02010-06-16 23:33:54 +00006554 BOOL usedDefaultChar = FALSE;
6555 BOOL *pusedDefaultChar;
6556 int mbcssize;
6557 Py_ssize_t n;
6558 PyObject *exc = NULL;
6559 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006560
6561 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006562
Victor Stinner554f3f02010-06-16 23:33:54 +00006563 /* check and handle 'errors' arg */
6564 if (errors==NULL || strcmp(errors, "strict")==0) {
6565 flags = WC_NO_BEST_FIT_CHARS;
6566 pusedDefaultChar = &usedDefaultChar;
6567 } else if (strcmp(errors, "replace")==0) {
6568 flags = 0;
6569 pusedDefaultChar = NULL;
6570 } else {
6571 PyErr_Format(PyExc_ValueError,
6572 "mbcs encoding does not support errors='%s'",
6573 errors);
6574 return -1;
6575 }
6576
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006577 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006578 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006579 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
6580 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 if (mbcssize == 0) {
6582 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6583 return -1;
6584 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006585 /* If we used a default char, then we failed! */
6586 if (pusedDefaultChar && *pusedDefaultChar)
6587 goto mbcs_encode_error;
6588 } else {
6589 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006590 }
6591
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006592 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 /* Create string object */
6594 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
6595 if (*repr == NULL)
6596 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006597 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006598 }
6599 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 /* Extend string object */
6601 n = PyBytes_Size(*repr);
6602 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
6603 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006604 }
6605
6606 /* Do the conversion */
6607 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006609 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
6610 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006611 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6612 return -1;
6613 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006614 if (pusedDefaultChar && *pusedDefaultChar)
6615 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006616 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006617 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006618
6619mbcs_encode_error:
6620 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
6621 Py_XDECREF(exc);
6622 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006623}
6624
Alexander Belopolsky40018472011-02-26 01:02:56 +00006625PyObject *
6626PyUnicode_EncodeMBCS(const Py_UNICODE *p,
6627 Py_ssize_t size,
6628 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006629{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006630 PyObject *repr = NULL;
6631 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00006632
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006633#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006635 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006636 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006637 else
6638#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006639 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006640
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006641 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 Py_XDECREF(repr);
6643 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006644 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006645
6646#ifdef NEED_RETRY
6647 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 p += INT_MAX;
6649 size -= INT_MAX;
6650 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006651 }
6652#endif
6653
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006654 return repr;
6655}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006656
Alexander Belopolsky40018472011-02-26 01:02:56 +00006657PyObject *
6658PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006659{
6660 if (!PyUnicode_Check(unicode)) {
6661 PyErr_BadArgument();
6662 return NULL;
6663 }
6664 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 PyUnicode_GET_SIZE(unicode),
6666 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006667}
6668
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006669#undef NEED_RETRY
6670
Victor Stinner99b95382011-07-04 14:23:54 +02006671#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006672
Guido van Rossumd57fd912000-03-10 22:53:23 +00006673/* --- Character Mapping Codec -------------------------------------------- */
6674
Alexander Belopolsky40018472011-02-26 01:02:56 +00006675PyObject *
6676PyUnicode_DecodeCharmap(const char *s,
6677 Py_ssize_t size,
6678 PyObject *mapping,
6679 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006680{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006682 Py_ssize_t startinpos;
6683 Py_ssize_t endinpos;
6684 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686 PyUnicodeObject *v;
6687 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006688 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006689 PyObject *errorHandler = NULL;
6690 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006691 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006692 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006693
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694 /* Default to Latin-1 */
6695 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006696 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006697
6698 v = _PyUnicode_New(size);
6699 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006701 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006705 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 mapstring = PyUnicode_AS_UNICODE(mapping);
6707 maplen = PyUnicode_GET_SIZE(mapping);
6708 while (s < e) {
6709 unsigned char ch = *s;
6710 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006711
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 if (ch < maplen)
6713 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006714
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 if (x == 0xfffe) {
6716 /* undefined mapping */
6717 outpos = p-PyUnicode_AS_UNICODE(v);
6718 startinpos = s-starts;
6719 endinpos = startinpos+1;
6720 if (unicode_decode_call_errorhandler(
6721 errors, &errorHandler,
6722 "charmap", "character maps to <undefined>",
6723 &starts, &e, &startinpos, &endinpos, &exc, &s,
6724 &v, &outpos, &p)) {
6725 goto onError;
6726 }
6727 continue;
6728 }
6729 *p++ = x;
6730 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006731 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006732 }
6733 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 while (s < e) {
6735 unsigned char ch = *s;
6736 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006737
Benjamin Peterson29060642009-01-31 22:14:21 +00006738 /* Get mapping (char ordinal -> integer, Unicode char or None) */
6739 w = PyLong_FromLong((long)ch);
6740 if (w == NULL)
6741 goto onError;
6742 x = PyObject_GetItem(mapping, w);
6743 Py_DECREF(w);
6744 if (x == NULL) {
6745 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6746 /* No mapping found means: mapping is undefined. */
6747 PyErr_Clear();
6748 x = Py_None;
6749 Py_INCREF(x);
6750 } else
6751 goto onError;
6752 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006753
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 /* Apply mapping */
6755 if (PyLong_Check(x)) {
6756 long value = PyLong_AS_LONG(x);
6757 if (value < 0 || value > 65535) {
6758 PyErr_SetString(PyExc_TypeError,
6759 "character mapping must be in range(65536)");
6760 Py_DECREF(x);
6761 goto onError;
6762 }
6763 *p++ = (Py_UNICODE)value;
6764 }
6765 else if (x == Py_None) {
6766 /* undefined mapping */
6767 outpos = p-PyUnicode_AS_UNICODE(v);
6768 startinpos = s-starts;
6769 endinpos = startinpos+1;
6770 if (unicode_decode_call_errorhandler(
6771 errors, &errorHandler,
6772 "charmap", "character maps to <undefined>",
6773 &starts, &e, &startinpos, &endinpos, &exc, &s,
6774 &v, &outpos, &p)) {
6775 Py_DECREF(x);
6776 goto onError;
6777 }
6778 Py_DECREF(x);
6779 continue;
6780 }
6781 else if (PyUnicode_Check(x)) {
6782 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006783
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 if (targetsize == 1)
6785 /* 1-1 mapping */
6786 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006787
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 else if (targetsize > 1) {
6789 /* 1-n mapping */
6790 if (targetsize > extrachars) {
6791 /* resize first */
6792 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
6793 Py_ssize_t needed = (targetsize - extrachars) + \
6794 (targetsize << 2);
6795 extrachars += needed;
6796 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02006797 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00006798 PyUnicode_GET_SIZE(v) + needed) < 0) {
6799 Py_DECREF(x);
6800 goto onError;
6801 }
6802 p = PyUnicode_AS_UNICODE(v) + oldpos;
6803 }
6804 Py_UNICODE_COPY(p,
6805 PyUnicode_AS_UNICODE(x),
6806 targetsize);
6807 p += targetsize;
6808 extrachars -= targetsize;
6809 }
6810 /* 1-0 mapping: skip the character */
6811 }
6812 else {
6813 /* wrong return value */
6814 PyErr_SetString(PyExc_TypeError,
6815 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006816 Py_DECREF(x);
6817 goto onError;
6818 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 Py_DECREF(x);
6820 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006821 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006822 }
6823 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006824 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006826 Py_XDECREF(errorHandler);
6827 Py_XDECREF(exc);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006828 if (PyUnicode_READY(v) == -1) {
6829 Py_DECREF(v);
6830 return NULL;
6831 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006832 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006833
Benjamin Peterson29060642009-01-31 22:14:21 +00006834 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006835 Py_XDECREF(errorHandler);
6836 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006837 Py_XDECREF(v);
6838 return NULL;
6839}
6840
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006841/* Charmap encoding: the lookup table */
6842
Alexander Belopolsky40018472011-02-26 01:02:56 +00006843struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00006844 PyObject_HEAD
6845 unsigned char level1[32];
6846 int count2, count3;
6847 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006848};
6849
6850static PyObject*
6851encoding_map_size(PyObject *obj, PyObject* args)
6852{
6853 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006854 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006856}
6857
6858static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006859 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 PyDoc_STR("Return the size (in bytes) of this object") },
6861 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006862};
6863
6864static void
6865encoding_map_dealloc(PyObject* o)
6866{
Benjamin Peterson14339b62009-01-31 16:36:08 +00006867 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006868}
6869
6870static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006871 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006872 "EncodingMap", /*tp_name*/
6873 sizeof(struct encoding_map), /*tp_basicsize*/
6874 0, /*tp_itemsize*/
6875 /* methods */
6876 encoding_map_dealloc, /*tp_dealloc*/
6877 0, /*tp_print*/
6878 0, /*tp_getattr*/
6879 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00006880 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 0, /*tp_repr*/
6882 0, /*tp_as_number*/
6883 0, /*tp_as_sequence*/
6884 0, /*tp_as_mapping*/
6885 0, /*tp_hash*/
6886 0, /*tp_call*/
6887 0, /*tp_str*/
6888 0, /*tp_getattro*/
6889 0, /*tp_setattro*/
6890 0, /*tp_as_buffer*/
6891 Py_TPFLAGS_DEFAULT, /*tp_flags*/
6892 0, /*tp_doc*/
6893 0, /*tp_traverse*/
6894 0, /*tp_clear*/
6895 0, /*tp_richcompare*/
6896 0, /*tp_weaklistoffset*/
6897 0, /*tp_iter*/
6898 0, /*tp_iternext*/
6899 encoding_map_methods, /*tp_methods*/
6900 0, /*tp_members*/
6901 0, /*tp_getset*/
6902 0, /*tp_base*/
6903 0, /*tp_dict*/
6904 0, /*tp_descr_get*/
6905 0, /*tp_descr_set*/
6906 0, /*tp_dictoffset*/
6907 0, /*tp_init*/
6908 0, /*tp_alloc*/
6909 0, /*tp_new*/
6910 0, /*tp_free*/
6911 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006912};
6913
6914PyObject*
6915PyUnicode_BuildEncodingMap(PyObject* string)
6916{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006917 PyObject *result;
6918 struct encoding_map *mresult;
6919 int i;
6920 int need_dict = 0;
6921 unsigned char level1[32];
6922 unsigned char level2[512];
6923 unsigned char *mlevel1, *mlevel2, *mlevel3;
6924 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006925 int kind;
6926 void *data;
6927 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006929 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006930 PyErr_BadArgument();
6931 return NULL;
6932 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006933 kind = PyUnicode_KIND(string);
6934 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006935 memset(level1, 0xFF, sizeof level1);
6936 memset(level2, 0xFF, sizeof level2);
6937
6938 /* If there isn't a one-to-one mapping of NULL to \0,
6939 or if there are non-BMP characters, we need to use
6940 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006941 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006942 need_dict = 1;
6943 for (i = 1; i < 256; i++) {
6944 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006945 ch = PyUnicode_READ(kind, data, i);
6946 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006947 need_dict = 1;
6948 break;
6949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006950 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006951 /* unmapped character */
6952 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006953 l1 = ch >> 11;
6954 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006955 if (level1[l1] == 0xFF)
6956 level1[l1] = count2++;
6957 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00006958 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006959 }
6960
6961 if (count2 >= 0xFF || count3 >= 0xFF)
6962 need_dict = 1;
6963
6964 if (need_dict) {
6965 PyObject *result = PyDict_New();
6966 PyObject *key, *value;
6967 if (!result)
6968 return NULL;
6969 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006970 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00006971 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006972 if (!key || !value)
6973 goto failed1;
6974 if (PyDict_SetItem(result, key, value) == -1)
6975 goto failed1;
6976 Py_DECREF(key);
6977 Py_DECREF(value);
6978 }
6979 return result;
6980 failed1:
6981 Py_XDECREF(key);
6982 Py_XDECREF(value);
6983 Py_DECREF(result);
6984 return NULL;
6985 }
6986
6987 /* Create a three-level trie */
6988 result = PyObject_MALLOC(sizeof(struct encoding_map) +
6989 16*count2 + 128*count3 - 1);
6990 if (!result)
6991 return PyErr_NoMemory();
6992 PyObject_Init(result, &EncodingMapType);
6993 mresult = (struct encoding_map*)result;
6994 mresult->count2 = count2;
6995 mresult->count3 = count3;
6996 mlevel1 = mresult->level1;
6997 mlevel2 = mresult->level23;
6998 mlevel3 = mresult->level23 + 16*count2;
6999 memcpy(mlevel1, level1, 32);
7000 memset(mlevel2, 0xFF, 16*count2);
7001 memset(mlevel3, 0, 128*count3);
7002 count3 = 0;
7003 for (i = 1; i < 256; i++) {
7004 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007005 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007006 /* unmapped character */
7007 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007008 o1 = PyUnicode_READ(kind, data, i)>>11;
7009 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007010 i2 = 16*mlevel1[o1] + o2;
7011 if (mlevel2[i2] == 0xFF)
7012 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007013 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007014 i3 = 128*mlevel2[i2] + o3;
7015 mlevel3[i3] = i;
7016 }
7017 return result;
7018}
7019
7020static int
7021encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7022{
7023 struct encoding_map *map = (struct encoding_map*)mapping;
7024 int l1 = c>>11;
7025 int l2 = (c>>7) & 0xF;
7026 int l3 = c & 0x7F;
7027 int i;
7028
7029#ifdef Py_UNICODE_WIDE
7030 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007031 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007032 }
7033#endif
7034 if (c == 0)
7035 return 0;
7036 /* level 1*/
7037 i = map->level1[l1];
7038 if (i == 0xFF) {
7039 return -1;
7040 }
7041 /* level 2*/
7042 i = map->level23[16*i+l2];
7043 if (i == 0xFF) {
7044 return -1;
7045 }
7046 /* level 3 */
7047 i = map->level23[16*map->count2 + 128*i + l3];
7048 if (i == 0) {
7049 return -1;
7050 }
7051 return i;
7052}
7053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007054/* Lookup the character ch in the mapping. If the character
7055 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007056 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007057static PyObject *
7058charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007059{
Christian Heimes217cfd12007-12-02 14:31:20 +00007060 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007061 PyObject *x;
7062
7063 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007064 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007065 x = PyObject_GetItem(mapping, w);
7066 Py_DECREF(w);
7067 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007068 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7069 /* No mapping found means: mapping is undefined. */
7070 PyErr_Clear();
7071 x = Py_None;
7072 Py_INCREF(x);
7073 return x;
7074 } else
7075 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007076 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007077 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007078 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007079 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007080 long value = PyLong_AS_LONG(x);
7081 if (value < 0 || value > 255) {
7082 PyErr_SetString(PyExc_TypeError,
7083 "character mapping must be in range(256)");
7084 Py_DECREF(x);
7085 return NULL;
7086 }
7087 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007088 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007089 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007090 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 /* wrong return value */
7093 PyErr_Format(PyExc_TypeError,
7094 "character mapping must return integer, bytes or None, not %.400s",
7095 x->ob_type->tp_name);
7096 Py_DECREF(x);
7097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007098 }
7099}
7100
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007101static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007102charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007103{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007104 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7105 /* exponentially overallocate to minimize reallocations */
7106 if (requiredsize < 2*outsize)
7107 requiredsize = 2*outsize;
7108 if (_PyBytes_Resize(outobj, requiredsize))
7109 return -1;
7110 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007111}
7112
Benjamin Peterson14339b62009-01-31 16:36:08 +00007113typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007114 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007115} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007116/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007117 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007118 space is available. Return a new reference to the object that
7119 was put in the output buffer, or Py_None, if the mapping was undefined
7120 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007121 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007122static charmapencode_result
7123charmapencode_output(Py_UNICODE c, PyObject *mapping,
7124 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007125{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007126 PyObject *rep;
7127 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007128 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007129
Christian Heimes90aa7642007-12-19 02:45:37 +00007130 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007131 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007132 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007133 if (res == -1)
7134 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007135 if (outsize<requiredsize)
7136 if (charmapencode_resize(outobj, outpos, requiredsize))
7137 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007138 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007139 outstart[(*outpos)++] = (char)res;
7140 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007141 }
7142
7143 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007144 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007145 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007146 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007147 Py_DECREF(rep);
7148 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007149 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007150 if (PyLong_Check(rep)) {
7151 Py_ssize_t requiredsize = *outpos+1;
7152 if (outsize<requiredsize)
7153 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7154 Py_DECREF(rep);
7155 return enc_EXCEPTION;
7156 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007157 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007158 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007159 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007160 else {
7161 const char *repchars = PyBytes_AS_STRING(rep);
7162 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7163 Py_ssize_t requiredsize = *outpos+repsize;
7164 if (outsize<requiredsize)
7165 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7166 Py_DECREF(rep);
7167 return enc_EXCEPTION;
7168 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007169 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007170 memcpy(outstart + *outpos, repchars, repsize);
7171 *outpos += repsize;
7172 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007173 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007174 Py_DECREF(rep);
7175 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007176}
7177
7178/* handle an error in PyUnicode_EncodeCharmap
7179 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007180static int
7181charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007182 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007183 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007184 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007185 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007186{
7187 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007188 Py_ssize_t repsize;
7189 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007190 Py_UNICODE *uni2;
7191 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007192 Py_ssize_t collstartpos = *inpos;
7193 Py_ssize_t collendpos = *inpos+1;
7194 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007195 char *encoding = "charmap";
7196 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007197 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007198
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007199 /* find all unencodable characters */
7200 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007201 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007202 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007203 int res = encoding_map_lookup(p[collendpos], mapping);
7204 if (res != -1)
7205 break;
7206 ++collendpos;
7207 continue;
7208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007209
Benjamin Peterson29060642009-01-31 22:14:21 +00007210 rep = charmapencode_lookup(p[collendpos], mapping);
7211 if (rep==NULL)
7212 return -1;
7213 else if (rep!=Py_None) {
7214 Py_DECREF(rep);
7215 break;
7216 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007217 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007218 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007219 }
7220 /* cache callback name lookup
7221 * (if not done yet, i.e. it's the first error) */
7222 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007223 if ((errors==NULL) || (!strcmp(errors, "strict")))
7224 *known_errorHandler = 1;
7225 else if (!strcmp(errors, "replace"))
7226 *known_errorHandler = 2;
7227 else if (!strcmp(errors, "ignore"))
7228 *known_errorHandler = 3;
7229 else if (!strcmp(errors, "xmlcharrefreplace"))
7230 *known_errorHandler = 4;
7231 else
7232 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007233 }
7234 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007235 case 1: /* strict */
7236 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7237 return -1;
7238 case 2: /* replace */
7239 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 x = charmapencode_output('?', mapping, res, respos);
7241 if (x==enc_EXCEPTION) {
7242 return -1;
7243 }
7244 else if (x==enc_FAILED) {
7245 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7246 return -1;
7247 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007248 }
7249 /* fall through */
7250 case 3: /* ignore */
7251 *inpos = collendpos;
7252 break;
7253 case 4: /* xmlcharrefreplace */
7254 /* generate replacement (temporarily (mis)uses p) */
7255 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007256 char buffer[2+29+1+1];
7257 char *cp;
7258 sprintf(buffer, "&#%d;", (int)p[collpos]);
7259 for (cp = buffer; *cp; ++cp) {
7260 x = charmapencode_output(*cp, mapping, res, respos);
7261 if (x==enc_EXCEPTION)
7262 return -1;
7263 else if (x==enc_FAILED) {
7264 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7265 return -1;
7266 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007267 }
7268 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007269 *inpos = collendpos;
7270 break;
7271 default:
7272 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007273 encoding, reason, p, size, exceptionObject,
7274 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007275 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007276 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007277 if (PyBytes_Check(repunicode)) {
7278 /* Directly copy bytes result to output. */
7279 Py_ssize_t outsize = PyBytes_Size(*res);
7280 Py_ssize_t requiredsize;
7281 repsize = PyBytes_Size(repunicode);
7282 requiredsize = *respos + repsize;
7283 if (requiredsize > outsize)
7284 /* Make room for all additional bytes. */
7285 if (charmapencode_resize(res, respos, requiredsize)) {
7286 Py_DECREF(repunicode);
7287 return -1;
7288 }
7289 memcpy(PyBytes_AsString(*res) + *respos,
7290 PyBytes_AsString(repunicode), repsize);
7291 *respos += repsize;
7292 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007293 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007294 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007296 /* generate replacement */
7297 repsize = PyUnicode_GET_SIZE(repunicode);
7298 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007299 x = charmapencode_output(*uni2, mapping, res, respos);
7300 if (x==enc_EXCEPTION) {
7301 return -1;
7302 }
7303 else if (x==enc_FAILED) {
7304 Py_DECREF(repunicode);
7305 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7306 return -1;
7307 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007308 }
7309 *inpos = newpos;
7310 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007311 }
7312 return 0;
7313}
7314
Alexander Belopolsky40018472011-02-26 01:02:56 +00007315PyObject *
7316PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7317 Py_ssize_t size,
7318 PyObject *mapping,
7319 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007320{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007321 /* output object */
7322 PyObject *res = NULL;
7323 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007324 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007325 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007326 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007327 PyObject *errorHandler = NULL;
7328 PyObject *exc = NULL;
7329 /* the following variable is used for caching string comparisons
7330 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7331 * 3=ignore, 4=xmlcharrefreplace */
7332 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007333
7334 /* Default to Latin-1 */
7335 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007336 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007337
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007338 /* allocate enough for a simple encoding without
7339 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007340 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007341 if (res == NULL)
7342 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007343 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007344 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007345
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007346 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007347 /* try to encode it */
7348 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7349 if (x==enc_EXCEPTION) /* error */
7350 goto onError;
7351 if (x==enc_FAILED) { /* unencodable character */
7352 if (charmap_encoding_error(p, size, &inpos, mapping,
7353 &exc,
7354 &known_errorHandler, &errorHandler, errors,
7355 &res, &respos)) {
7356 goto onError;
7357 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007358 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007359 else
7360 /* done with this character => adjust input position */
7361 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007362 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007363
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007364 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007365 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007366 if (_PyBytes_Resize(&res, respos) < 0)
7367 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007368
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007369 Py_XDECREF(exc);
7370 Py_XDECREF(errorHandler);
7371 return res;
7372
Benjamin Peterson29060642009-01-31 22:14:21 +00007373 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007374 Py_XDECREF(res);
7375 Py_XDECREF(exc);
7376 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007377 return NULL;
7378}
7379
Alexander Belopolsky40018472011-02-26 01:02:56 +00007380PyObject *
7381PyUnicode_AsCharmapString(PyObject *unicode,
7382 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007383{
7384 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007385 PyErr_BadArgument();
7386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007387 }
7388 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007389 PyUnicode_GET_SIZE(unicode),
7390 mapping,
7391 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007392}
7393
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007394/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007395static void
7396make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007397 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007398 Py_ssize_t startpos, Py_ssize_t endpos,
7399 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007400{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007401 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007402 *exceptionObject = _PyUnicodeTranslateError_Create(
7403 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007404 }
7405 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007406 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7407 goto onError;
7408 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7409 goto onError;
7410 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7411 goto onError;
7412 return;
7413 onError:
7414 Py_DECREF(*exceptionObject);
7415 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007416 }
7417}
7418
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007419/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007420static void
7421raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007422 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007423 Py_ssize_t startpos, Py_ssize_t endpos,
7424 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007425{
7426 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007427 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007428 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007430}
7431
7432/* error handling callback helper:
7433 build arguments, call the callback and check the arguments,
7434 put the result into newpos and return the replacement string, which
7435 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007436static PyObject *
7437unicode_translate_call_errorhandler(const char *errors,
7438 PyObject **errorHandler,
7439 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007440 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007441 Py_ssize_t startpos, Py_ssize_t endpos,
7442 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007443{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007444 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007445
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007446 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007447 PyObject *restuple;
7448 PyObject *resunicode;
7449
7450 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007451 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007452 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007453 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007454 }
7455
7456 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007457 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007458 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007459 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007460
7461 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007462 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007463 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007464 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007465 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007466 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007467 Py_DECREF(restuple);
7468 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007469 }
7470 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007471 &resunicode, &i_newpos)) {
7472 Py_DECREF(restuple);
7473 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007474 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007475 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007476 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007477 else
7478 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007479 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007480 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7481 Py_DECREF(restuple);
7482 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007483 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007484 Py_INCREF(resunicode);
7485 Py_DECREF(restuple);
7486 return resunicode;
7487}
7488
7489/* Lookup the character ch in the mapping and put the result in result,
7490 which must be decrefed by the caller.
7491 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007492static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007493charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007494{
Christian Heimes217cfd12007-12-02 14:31:20 +00007495 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007496 PyObject *x;
7497
7498 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007500 x = PyObject_GetItem(mapping, w);
7501 Py_DECREF(w);
7502 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7504 /* No mapping found means: use 1:1 mapping. */
7505 PyErr_Clear();
7506 *result = NULL;
7507 return 0;
7508 } else
7509 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007510 }
7511 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007512 *result = x;
7513 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007514 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007515 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007516 long value = PyLong_AS_LONG(x);
7517 long max = PyUnicode_GetMax();
7518 if (value < 0 || value > max) {
7519 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007520 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007521 Py_DECREF(x);
7522 return -1;
7523 }
7524 *result = x;
7525 return 0;
7526 }
7527 else if (PyUnicode_Check(x)) {
7528 *result = x;
7529 return 0;
7530 }
7531 else {
7532 /* wrong return value */
7533 PyErr_SetString(PyExc_TypeError,
7534 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007535 Py_DECREF(x);
7536 return -1;
7537 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007538}
7539/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007540 if not reallocate and adjust various state variables.
7541 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007542static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007543charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007544 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007545{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007546 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007547 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007548 /* exponentially overallocate to minimize reallocations */
7549 if (requiredsize < 2 * oldsize)
7550 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007551 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7552 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007554 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007555 }
7556 return 0;
7557}
7558/* lookup the character, put the result in the output string and adjust
7559 various state variables. Return a new reference to the object that
7560 was put in the output buffer in *result, or Py_None, if the mapping was
7561 undefined (in which case no character was written).
7562 The called must decref result.
7563 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007564static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007565charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
7566 PyObject *mapping, Py_UCS4 **output,
7567 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007568 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007570 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
7571 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00007572 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007573 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007574 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007575 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007576 }
7577 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00007579 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007581 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007582 }
7583 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007584 Py_ssize_t repsize;
7585 if (PyUnicode_READY(*res) == -1)
7586 return -1;
7587 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00007588 if (repsize==1) {
7589 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007590 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 }
7592 else if (repsize!=0) {
7593 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007594 Py_ssize_t requiredsize = *opos +
7595 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007597 Py_ssize_t i;
7598 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007600 for(i = 0; i < repsize; i++)
7601 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00007602 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007603 }
7604 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007606 return 0;
7607}
7608
Alexander Belopolsky40018472011-02-26 01:02:56 +00007609PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007610_PyUnicode_TranslateCharmap(PyObject *input,
7611 PyObject *mapping,
7612 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007614 /* input object */
7615 char *idata;
7616 Py_ssize_t size, i;
7617 int kind;
7618 /* output buffer */
7619 Py_UCS4 *output = NULL;
7620 Py_ssize_t osize;
7621 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007622 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007623 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007624 char *reason = "character maps to <undefined>";
7625 PyObject *errorHandler = NULL;
7626 PyObject *exc = NULL;
7627 /* the following variable is used for caching string comparisons
7628 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7629 * 3=ignore, 4=xmlcharrefreplace */
7630 int known_errorHandler = -1;
7631
Guido van Rossumd57fd912000-03-10 22:53:23 +00007632 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 PyErr_BadArgument();
7634 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007635 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007637 if (PyUnicode_READY(input) == -1)
7638 return NULL;
7639 idata = (char*)PyUnicode_DATA(input);
7640 kind = PyUnicode_KIND(input);
7641 size = PyUnicode_GET_LENGTH(input);
7642 i = 0;
7643
7644 if (size == 0) {
7645 Py_INCREF(input);
7646 return input;
7647 }
7648
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007649 /* allocate enough for a simple 1:1 translation without
7650 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007651 osize = size;
7652 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
7653 opos = 0;
7654 if (output == NULL) {
7655 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007656 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007659 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007660 /* try to encode it */
7661 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007662 if (charmaptranslate_output(input, i, mapping,
7663 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007664 Py_XDECREF(x);
7665 goto onError;
7666 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007667 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007669 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00007670 else { /* untranslatable character */
7671 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
7672 Py_ssize_t repsize;
7673 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007674 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00007675 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007676 Py_ssize_t collstart = i;
7677 Py_ssize_t collend = i+1;
7678 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007679
Benjamin Peterson29060642009-01-31 22:14:21 +00007680 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007681 while (collend < size) {
7682 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 goto onError;
7684 Py_XDECREF(x);
7685 if (x!=Py_None)
7686 break;
7687 ++collend;
7688 }
7689 /* cache callback name lookup
7690 * (if not done yet, i.e. it's the first error) */
7691 if (known_errorHandler==-1) {
7692 if ((errors==NULL) || (!strcmp(errors, "strict")))
7693 known_errorHandler = 1;
7694 else if (!strcmp(errors, "replace"))
7695 known_errorHandler = 2;
7696 else if (!strcmp(errors, "ignore"))
7697 known_errorHandler = 3;
7698 else if (!strcmp(errors, "xmlcharrefreplace"))
7699 known_errorHandler = 4;
7700 else
7701 known_errorHandler = 0;
7702 }
7703 switch (known_errorHandler) {
7704 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007705 raise_translate_exception(&exc, input, collstart,
7706 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007707 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 case 2: /* replace */
7709 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007710 for (coll = collstart; coll<collend; coll++)
7711 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00007712 /* fall through */
7713 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007714 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007715 break;
7716 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007717 /* generate replacement (temporarily (mis)uses i) */
7718 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 char buffer[2+29+1+1];
7720 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007721 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
7722 if (charmaptranslate_makespace(&output, &osize,
7723 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007724 goto onError;
7725 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007726 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007728 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 break;
7730 default:
7731 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007732 reason, input, &exc,
7733 collstart, collend, &newpos);
7734 if (repunicode == NULL || PyUnicode_READY(repunicode) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00007735 goto onError;
7736 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007737 repsize = PyUnicode_GET_LENGTH(repunicode);
7738 if (charmaptranslate_makespace(&output, &osize,
7739 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 Py_DECREF(repunicode);
7741 goto onError;
7742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007743 for (uni2 = 0; repsize-->0; ++uni2)
7744 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
7745 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007747 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007748 }
7749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007750 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
7751 if (!res)
7752 goto onError;
7753 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007754 Py_XDECREF(exc);
7755 Py_XDECREF(errorHandler);
7756 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007757
Benjamin Peterson29060642009-01-31 22:14:21 +00007758 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007759 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007760 Py_XDECREF(exc);
7761 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762 return NULL;
7763}
7764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007765/* Deprecated. Use PyUnicode_Translate instead. */
7766PyObject *
7767PyUnicode_TranslateCharmap(const Py_UNICODE *p,
7768 Py_ssize_t size,
7769 PyObject *mapping,
7770 const char *errors)
7771{
7772 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7773 if (!unicode)
7774 return NULL;
7775 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
7776}
7777
Alexander Belopolsky40018472011-02-26 01:02:56 +00007778PyObject *
7779PyUnicode_Translate(PyObject *str,
7780 PyObject *mapping,
7781 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007782{
7783 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00007784
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785 str = PyUnicode_FromObject(str);
7786 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007788 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789 Py_DECREF(str);
7790 return result;
Tim Petersced69f82003-09-16 20:30:58 +00007791
Benjamin Peterson29060642009-01-31 22:14:21 +00007792 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007793 Py_XDECREF(str);
7794 return NULL;
7795}
Tim Petersced69f82003-09-16 20:30:58 +00007796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007797static Py_UCS4
7798fix_decimal_and_space_to_ascii(PyUnicodeObject *self)
7799{
7800 /* No need to call PyUnicode_READY(self) because this function is only
7801 called as a callback from fixup() which does it already. */
7802 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
7803 const int kind = PyUnicode_KIND(self);
7804 void *data = PyUnicode_DATA(self);
7805 Py_UCS4 maxchar = 0, ch, fixed;
7806 Py_ssize_t i;
7807
7808 for (i = 0; i < len; ++i) {
7809 ch = PyUnicode_READ(kind, data, i);
7810 fixed = 0;
7811 if (ch > 127) {
7812 if (Py_UNICODE_ISSPACE(ch))
7813 fixed = ' ';
7814 else {
7815 const int decimal = Py_UNICODE_TODECIMAL(ch);
7816 if (decimal >= 0)
7817 fixed = '0' + decimal;
7818 }
7819 if (fixed != 0) {
7820 if (fixed > maxchar)
7821 maxchar = fixed;
7822 PyUnicode_WRITE(kind, data, i, fixed);
7823 }
7824 else if (ch > maxchar)
7825 maxchar = ch;
7826 }
7827 else if (ch > maxchar)
7828 maxchar = ch;
7829 }
7830
7831 return maxchar;
7832}
7833
7834PyObject *
7835_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
7836{
7837 if (!PyUnicode_Check(unicode)) {
7838 PyErr_BadInternalCall();
7839 return NULL;
7840 }
7841 if (PyUnicode_READY(unicode) == -1)
7842 return NULL;
7843 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
7844 /* If the string is already ASCII, just return the same string */
7845 Py_INCREF(unicode);
7846 return unicode;
7847 }
7848 return fixup((PyUnicodeObject *)unicode, fix_decimal_and_space_to_ascii);
7849}
7850
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007851PyObject *
7852PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
7853 Py_ssize_t length)
7854{
7855 PyObject *result;
7856 Py_UNICODE *p; /* write pointer into result */
7857 Py_ssize_t i;
7858 /* Copy to a new string */
7859 result = (PyObject *)_PyUnicode_New(length);
7860 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
7861 if (result == NULL)
7862 return result;
7863 p = PyUnicode_AS_UNICODE(result);
7864 /* Iterate over code points */
7865 for (i = 0; i < length; i++) {
7866 Py_UNICODE ch =s[i];
7867 if (ch > 127) {
7868 int decimal = Py_UNICODE_TODECIMAL(ch);
7869 if (decimal >= 0)
7870 p[i] = '0' + decimal;
7871 }
7872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007873 if (PyUnicode_READY((PyUnicodeObject*)result) == -1) {
7874 Py_DECREF(result);
7875 return NULL;
7876 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007877 return result;
7878}
Guido van Rossum9e896b32000-04-05 20:11:21 +00007879/* --- Decimal Encoder ---------------------------------------------------- */
7880
Alexander Belopolsky40018472011-02-26 01:02:56 +00007881int
7882PyUnicode_EncodeDecimal(Py_UNICODE *s,
7883 Py_ssize_t length,
7884 char *output,
7885 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00007886{
7887 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007888 PyObject *errorHandler = NULL;
7889 PyObject *exc = NULL;
7890 const char *encoding = "decimal";
7891 const char *reason = "invalid decimal Unicode string";
7892 /* the following variable is used for caching string comparisons
7893 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
7894 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007895
7896 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007897 PyErr_BadArgument();
7898 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00007899 }
7900
7901 p = s;
7902 end = s + length;
7903 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 register Py_UNICODE ch = *p;
7905 int decimal;
7906 PyObject *repunicode;
7907 Py_ssize_t repsize;
7908 Py_ssize_t newpos;
7909 Py_UNICODE *uni2;
7910 Py_UNICODE *collstart;
7911 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00007912
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007914 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 ++p;
7916 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007917 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 decimal = Py_UNICODE_TODECIMAL(ch);
7919 if (decimal >= 0) {
7920 *output++ = '0' + decimal;
7921 ++p;
7922 continue;
7923 }
7924 if (0 < ch && ch < 256) {
7925 *output++ = (char)ch;
7926 ++p;
7927 continue;
7928 }
7929 /* All other characters are considered unencodable */
7930 collstart = p;
7931 collend = p+1;
7932 while (collend < end) {
7933 if ((0 < *collend && *collend < 256) ||
7934 !Py_UNICODE_ISSPACE(*collend) ||
7935 Py_UNICODE_TODECIMAL(*collend))
7936 break;
7937 }
7938 /* cache callback name lookup
7939 * (if not done yet, i.e. it's the first error) */
7940 if (known_errorHandler==-1) {
7941 if ((errors==NULL) || (!strcmp(errors, "strict")))
7942 known_errorHandler = 1;
7943 else if (!strcmp(errors, "replace"))
7944 known_errorHandler = 2;
7945 else if (!strcmp(errors, "ignore"))
7946 known_errorHandler = 3;
7947 else if (!strcmp(errors, "xmlcharrefreplace"))
7948 known_errorHandler = 4;
7949 else
7950 known_errorHandler = 0;
7951 }
7952 switch (known_errorHandler) {
7953 case 1: /* strict */
7954 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
7955 goto onError;
7956 case 2: /* replace */
7957 for (p = collstart; p < collend; ++p)
7958 *output++ = '?';
7959 /* fall through */
7960 case 3: /* ignore */
7961 p = collend;
7962 break;
7963 case 4: /* xmlcharrefreplace */
7964 /* generate replacement (temporarily (mis)uses p) */
7965 for (p = collstart; p < collend; ++p)
7966 output += sprintf(output, "&#%d;", (int)*p);
7967 p = collend;
7968 break;
7969 default:
7970 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
7971 encoding, reason, s, length, &exc,
7972 collstart-s, collend-s, &newpos);
7973 if (repunicode == NULL)
7974 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007975 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00007976 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007977 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
7978 Py_DECREF(repunicode);
7979 goto onError;
7980 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 /* generate replacement */
7982 repsize = PyUnicode_GET_SIZE(repunicode);
7983 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
7984 Py_UNICODE ch = *uni2;
7985 if (Py_UNICODE_ISSPACE(ch))
7986 *output++ = ' ';
7987 else {
7988 decimal = Py_UNICODE_TODECIMAL(ch);
7989 if (decimal >= 0)
7990 *output++ = '0' + decimal;
7991 else if (0 < ch && ch < 256)
7992 *output++ = (char)ch;
7993 else {
7994 Py_DECREF(repunicode);
7995 raise_encode_exception(&exc, encoding,
7996 s, length, collstart-s, collend-s, reason);
7997 goto onError;
7998 }
7999 }
8000 }
8001 p = s + newpos;
8002 Py_DECREF(repunicode);
8003 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008004 }
8005 /* 0-terminate the output string */
8006 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008007 Py_XDECREF(exc);
8008 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008009 return 0;
8010
Benjamin Peterson29060642009-01-31 22:14:21 +00008011 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008012 Py_XDECREF(exc);
8013 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008014 return -1;
8015}
8016
Guido van Rossumd57fd912000-03-10 22:53:23 +00008017/* --- Helpers ------------------------------------------------------------ */
8018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008019#include "stringlib/ucs1lib.h"
8020#include "stringlib/fastsearch.h"
8021#include "stringlib/partition.h"
8022#include "stringlib/split.h"
8023#include "stringlib/count.h"
8024#include "stringlib/find.h"
8025#include "stringlib/localeutil.h"
8026#include "stringlib/undef.h"
8027
8028#include "stringlib/ucs2lib.h"
8029#include "stringlib/fastsearch.h"
8030#include "stringlib/partition.h"
8031#include "stringlib/split.h"
8032#include "stringlib/count.h"
8033#include "stringlib/find.h"
8034#include "stringlib/localeutil.h"
8035#include "stringlib/undef.h"
8036
8037#include "stringlib/ucs4lib.h"
8038#include "stringlib/fastsearch.h"
8039#include "stringlib/partition.h"
8040#include "stringlib/split.h"
8041#include "stringlib/count.h"
8042#include "stringlib/find.h"
8043#include "stringlib/localeutil.h"
8044#include "stringlib/undef.h"
8045
8046static Py_ssize_t
8047any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
8048 const Py_UCS1*, Py_ssize_t,
8049 Py_ssize_t, Py_ssize_t),
8050 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
8051 const Py_UCS2*, Py_ssize_t,
8052 Py_ssize_t, Py_ssize_t),
8053 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
8054 const Py_UCS4*, Py_ssize_t,
8055 Py_ssize_t, Py_ssize_t),
8056 PyObject* s1, PyObject* s2,
8057 Py_ssize_t start,
8058 Py_ssize_t end)
8059{
8060 int kind1, kind2, kind;
8061 void *buf1, *buf2;
8062 Py_ssize_t len1, len2, result;
8063
8064 kind1 = PyUnicode_KIND(s1);
8065 kind2 = PyUnicode_KIND(s2);
8066 kind = kind1 > kind2 ? kind1 : kind2;
8067 buf1 = PyUnicode_DATA(s1);
8068 buf2 = PyUnicode_DATA(s2);
8069 if (kind1 != kind)
8070 buf1 = _PyUnicode_AsKind(s1, kind);
8071 if (!buf1)
8072 return -2;
8073 if (kind2 != kind)
8074 buf2 = _PyUnicode_AsKind(s2, kind);
8075 if (!buf2) {
8076 if (kind1 != kind) PyMem_Free(buf1);
8077 return -2;
8078 }
8079 len1 = PyUnicode_GET_LENGTH(s1);
8080 len2 = PyUnicode_GET_LENGTH(s2);
8081
8082 switch(kind) {
8083 case PyUnicode_1BYTE_KIND:
8084 result = ucs1(buf1, len1, buf2, len2, start, end);
8085 break;
8086 case PyUnicode_2BYTE_KIND:
8087 result = ucs2(buf1, len1, buf2, len2, start, end);
8088 break;
8089 case PyUnicode_4BYTE_KIND:
8090 result = ucs4(buf1, len1, buf2, len2, start, end);
8091 break;
8092 default:
8093 assert(0); result = -2;
8094 }
8095
8096 if (kind1 != kind)
8097 PyMem_Free(buf1);
8098 if (kind2 != kind)
8099 PyMem_Free(buf2);
8100
8101 return result;
8102}
8103
8104Py_ssize_t
8105_PyUnicode_InsertThousandsGrouping(int kind, void *data,
8106 Py_ssize_t n_buffer,
8107 void *digits, Py_ssize_t n_digits,
8108 Py_ssize_t min_width,
8109 const char *grouping,
8110 const char *thousands_sep)
8111{
8112 switch(kind) {
8113 case PyUnicode_1BYTE_KIND:
8114 return _PyUnicode_ucs1_InsertThousandsGrouping(
8115 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8116 min_width, grouping, thousands_sep);
8117 case PyUnicode_2BYTE_KIND:
8118 return _PyUnicode_ucs2_InsertThousandsGrouping(
8119 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8120 min_width, grouping, thousands_sep);
8121 case PyUnicode_4BYTE_KIND:
8122 return _PyUnicode_ucs4_InsertThousandsGrouping(
8123 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8124 min_width, grouping, thousands_sep);
8125 }
8126 assert(0);
8127 return -1;
8128}
8129
8130
Eric Smith8c663262007-08-25 02:26:07 +00008131#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008132#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008133
Thomas Wouters477c8d52006-05-27 19:21:47 +00008134#include "stringlib/count.h"
8135#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008136
Thomas Wouters477c8d52006-05-27 19:21:47 +00008137/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008138#define ADJUST_INDICES(start, end, len) \
8139 if (end > len) \
8140 end = len; \
8141 else if (end < 0) { \
8142 end += len; \
8143 if (end < 0) \
8144 end = 0; \
8145 } \
8146 if (start < 0) { \
8147 start += len; \
8148 if (start < 0) \
8149 start = 0; \
8150 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008151
Alexander Belopolsky40018472011-02-26 01:02:56 +00008152Py_ssize_t
8153PyUnicode_Count(PyObject *str,
8154 PyObject *substr,
8155 Py_ssize_t start,
8156 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008157{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008158 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008159 PyUnicodeObject* str_obj;
8160 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008161 int kind1, kind2, kind;
8162 void *buf1 = NULL, *buf2 = NULL;
8163 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008164
Thomas Wouters477c8d52006-05-27 19:21:47 +00008165 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008166 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008168 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008169 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 Py_DECREF(str_obj);
8171 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008172 }
Tim Petersced69f82003-09-16 20:30:58 +00008173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008174 kind1 = PyUnicode_KIND(str_obj);
8175 kind2 = PyUnicode_KIND(sub_obj);
8176 kind = kind1 > kind2 ? kind1 : kind2;
8177 buf1 = PyUnicode_DATA(str_obj);
8178 if (kind1 != kind)
8179 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8180 if (!buf1)
8181 goto onError;
8182 buf2 = PyUnicode_DATA(sub_obj);
8183 if (kind2 != kind)
8184 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8185 if (!buf2)
8186 goto onError;
8187 len1 = PyUnicode_GET_LENGTH(str_obj);
8188 len2 = PyUnicode_GET_LENGTH(sub_obj);
8189
8190 ADJUST_INDICES(start, end, len1);
8191 switch(kind) {
8192 case PyUnicode_1BYTE_KIND:
8193 result = ucs1lib_count(
8194 ((Py_UCS1*)buf1) + start, end - start,
8195 buf2, len2, PY_SSIZE_T_MAX
8196 );
8197 break;
8198 case PyUnicode_2BYTE_KIND:
8199 result = ucs2lib_count(
8200 ((Py_UCS2*)buf1) + start, end - start,
8201 buf2, len2, PY_SSIZE_T_MAX
8202 );
8203 break;
8204 case PyUnicode_4BYTE_KIND:
8205 result = ucs4lib_count(
8206 ((Py_UCS4*)buf1) + start, end - start,
8207 buf2, len2, PY_SSIZE_T_MAX
8208 );
8209 break;
8210 default:
8211 assert(0); result = 0;
8212 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008213
8214 Py_DECREF(sub_obj);
8215 Py_DECREF(str_obj);
8216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217 if (kind1 != kind)
8218 PyMem_Free(buf1);
8219 if (kind2 != kind)
8220 PyMem_Free(buf2);
8221
Guido van Rossumd57fd912000-03-10 22:53:23 +00008222 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008223 onError:
8224 Py_DECREF(sub_obj);
8225 Py_DECREF(str_obj);
8226 if (kind1 != kind && buf1)
8227 PyMem_Free(buf1);
8228 if (kind2 != kind && buf2)
8229 PyMem_Free(buf2);
8230 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008231}
8232
Alexander Belopolsky40018472011-02-26 01:02:56 +00008233Py_ssize_t
8234PyUnicode_Find(PyObject *str,
8235 PyObject *sub,
8236 Py_ssize_t start,
8237 Py_ssize_t end,
8238 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008239{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008240 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008241
Guido van Rossumd57fd912000-03-10 22:53:23 +00008242 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008243 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008245 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008246 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 Py_DECREF(str);
8248 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249 }
Tim Petersced69f82003-09-16 20:30:58 +00008250
Thomas Wouters477c8d52006-05-27 19:21:47 +00008251 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008252 result = any_find_slice(
8253 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
8254 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008255 );
8256 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008257 result = any_find_slice(
8258 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
8259 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008260 );
8261
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008263 Py_DECREF(sub);
8264
Guido van Rossumd57fd912000-03-10 22:53:23 +00008265 return result;
8266}
8267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008268Py_ssize_t
8269PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8270 Py_ssize_t start, Py_ssize_t end,
8271 int direction)
8272{
8273 char *result;
8274 int kind;
8275 if (PyUnicode_READY(str) == -1)
8276 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008277 if (start < 0 || end < 0) {
8278 PyErr_SetString(PyExc_IndexError, "string index out of range");
8279 return -2;
8280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008281 if (end > PyUnicode_GET_LENGTH(str))
8282 end = PyUnicode_GET_LENGTH(str);
8283 kind = PyUnicode_KIND(str);
8284 result = findchar(PyUnicode_1BYTE_DATA(str)
8285 + PyUnicode_KIND_SIZE(kind, start),
8286 kind,
8287 end-start, ch, direction);
8288 if (!result)
8289 return -1;
8290 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8291}
8292
Alexander Belopolsky40018472011-02-26 01:02:56 +00008293static int
8294tailmatch(PyUnicodeObject *self,
8295 PyUnicodeObject *substring,
8296 Py_ssize_t start,
8297 Py_ssize_t end,
8298 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008300 int kind_self;
8301 int kind_sub;
8302 void *data_self;
8303 void *data_sub;
8304 Py_ssize_t offset;
8305 Py_ssize_t i;
8306 Py_ssize_t end_sub;
8307
8308 if (PyUnicode_READY(self) == -1 ||
8309 PyUnicode_READY(substring) == -1)
8310 return 0;
8311
8312 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008313 return 1;
8314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008315 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8316 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008317 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008320 kind_self = PyUnicode_KIND(self);
8321 data_self = PyUnicode_DATA(self);
8322 kind_sub = PyUnicode_KIND(substring);
8323 data_sub = PyUnicode_DATA(substring);
8324 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8325
8326 if (direction > 0)
8327 offset = end;
8328 else
8329 offset = start;
8330
8331 if (PyUnicode_READ(kind_self, data_self, offset) ==
8332 PyUnicode_READ(kind_sub, data_sub, 0) &&
8333 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8334 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8335 /* If both are of the same kind, memcmp is sufficient */
8336 if (kind_self == kind_sub) {
8337 return ! memcmp((char *)data_self +
8338 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8339 data_sub,
8340 PyUnicode_GET_LENGTH(substring) *
8341 PyUnicode_CHARACTER_SIZE(substring));
8342 }
8343 /* otherwise we have to compare each character by first accesing it */
8344 else {
8345 /* We do not need to compare 0 and len(substring)-1 because
8346 the if statement above ensured already that they are equal
8347 when we end up here. */
8348 // TODO: honor direction and do a forward or backwards search
8349 for (i = 1; i < end_sub; ++i) {
8350 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8351 PyUnicode_READ(kind_sub, data_sub, i))
8352 return 0;
8353 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008355 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356 }
8357
8358 return 0;
8359}
8360
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361Py_ssize_t
8362PyUnicode_Tailmatch(PyObject *str,
8363 PyObject *substr,
8364 Py_ssize_t start,
8365 Py_ssize_t end,
8366 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008367{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008368 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008369
Guido van Rossumd57fd912000-03-10 22:53:23 +00008370 str = PyUnicode_FromObject(str);
8371 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008373 substr = PyUnicode_FromObject(substr);
8374 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 Py_DECREF(str);
8376 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377 }
Tim Petersced69f82003-09-16 20:30:58 +00008378
Guido van Rossumd57fd912000-03-10 22:53:23 +00008379 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 (PyUnicodeObject *)substr,
8381 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008382 Py_DECREF(str);
8383 Py_DECREF(substr);
8384 return result;
8385}
8386
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387/* Apply fixfct filter to the Unicode object self and return a
8388 reference to the modified object */
8389
Alexander Belopolsky40018472011-02-26 01:02:56 +00008390static PyObject *
8391fixup(PyUnicodeObject *self,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 Py_UCS4 (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008393{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008394 PyObject *u;
8395 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008396
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397 if (PyUnicode_READY(self) == -1)
8398 return NULL;
8399 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8400 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8401 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008403 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8406 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408 /* fix functions return the new maximum character in a string,
8409 if the kind of the resulting unicode object does not change,
8410 everything is fine. Otherwise we need to change the string kind
8411 and re-run the fix function. */
8412 maxchar_new = fixfct((PyUnicodeObject*)u);
8413 if (maxchar_new == 0)
8414 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8415 else if (maxchar_new <= 127)
8416 maxchar_new = 127;
8417 else if (maxchar_new <= 255)
8418 maxchar_new = 255;
8419 else if (maxchar_new <= 65535)
8420 maxchar_new = 65535;
8421 else
8422 maxchar_new = 1114111; /* 0x10ffff */
8423
8424 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 /* fixfct should return TRUE if it modified the buffer. If
8426 FALSE, return a reference to the original buffer instead
8427 (to save space, not time) */
8428 Py_INCREF(self);
8429 Py_DECREF(u);
8430 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 else if (maxchar_new == maxchar_old) {
8433 return u;
8434 }
8435 else {
8436 /* In case the maximum character changed, we need to
8437 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008438 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 if (v == NULL) {
8440 Py_DECREF(u);
8441 return NULL;
8442 }
8443 if (maxchar_new > maxchar_old) {
8444 /* If the maxchar increased so that the kind changed, not all
8445 characters are representable anymore and we need to fix the
8446 string again. This only happens in very few cases. */
Victor Stinner157f83f2011-09-28 21:41:31 +02008447 if (PyUnicode_CopyCharacters(v, 0,
8448 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008449 PyUnicode_GET_LENGTH(self)) < 0)
8450 {
8451 Py_DECREF(u);
8452 return NULL;
8453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 maxchar_old = fixfct((PyUnicodeObject*)v);
8455 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8456 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008457 else {
Victor Stinner157f83f2011-09-28 21:41:31 +02008458 if (PyUnicode_CopyCharacters(v, 0,
8459 u, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008460 PyUnicode_GET_LENGTH(self)) < 0)
8461 {
8462 Py_DECREF(u);
8463 return NULL;
8464 }
8465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008466
8467 Py_DECREF(u);
8468 return v;
8469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008470}
8471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008473fixupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 /* No need to call PyUnicode_READY(self) because this function is only
8476 called as a callback from fixup() which does it already. */
8477 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8478 const int kind = PyUnicode_KIND(self);
8479 void *data = PyUnicode_DATA(self);
8480 int touched = 0;
8481 Py_UCS4 maxchar = 0;
8482 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 for (i = 0; i < len; ++i) {
8485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8486 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8487 if (up != ch) {
8488 if (up > maxchar)
8489 maxchar = up;
8490 PyUnicode_WRITE(kind, data, i, up);
8491 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493 else if (ch > maxchar)
8494 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008495 }
8496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008497 if (touched)
8498 return maxchar;
8499 else
8500 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008501}
8502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008504fixlower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8507 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8508 const int kind = PyUnicode_KIND(self);
8509 void *data = PyUnicode_DATA(self);
8510 int touched = 0;
8511 Py_UCS4 maxchar = 0;
8512 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 for(i = 0; i < len; ++i) {
8515 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8516 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8517 if (lo != ch) {
8518 if (lo > maxchar)
8519 maxchar = lo;
8520 PyUnicode_WRITE(kind, data, i, lo);
8521 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008523 else if (ch > maxchar)
8524 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525 }
8526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 if (touched)
8528 return maxchar;
8529 else
8530 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008531}
8532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008534fixswapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008535{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8537 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8538 const int kind = PyUnicode_KIND(self);
8539 void *data = PyUnicode_DATA(self);
8540 int touched = 0;
8541 Py_UCS4 maxchar = 0;
8542 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008544 for(i = 0; i < len; ++i) {
8545 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8546 Py_UCS4 nu = 0;
8547
8548 if (Py_UNICODE_ISUPPER(ch))
8549 nu = Py_UNICODE_TOLOWER(ch);
8550 else if (Py_UNICODE_ISLOWER(ch))
8551 nu = Py_UNICODE_TOUPPER(ch);
8552
8553 if (nu != 0) {
8554 if (nu > maxchar)
8555 maxchar = nu;
8556 PyUnicode_WRITE(kind, data, i, nu);
8557 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 else if (ch > maxchar)
8560 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561 }
8562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 if (touched)
8564 return maxchar;
8565 else
8566 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008567}
8568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008570fixcapitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8573 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8574 const int kind = PyUnicode_KIND(self);
8575 void *data = PyUnicode_DATA(self);
8576 int touched = 0;
8577 Py_UCS4 maxchar = 0;
8578 Py_ssize_t i = 0;
8579 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00008580
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008581 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583
8584 ch = PyUnicode_READ(kind, data, i);
8585 if (!Py_UNICODE_ISUPPER(ch)) {
8586 maxchar = Py_UNICODE_TOUPPER(ch);
8587 PyUnicode_WRITE(kind, data, i, maxchar);
8588 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 ++i;
8591 for(; i < len; ++i) {
8592 ch = PyUnicode_READ(kind, data, i);
8593 if (!Py_UNICODE_ISLOWER(ch)) {
8594 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8595 if (lo > maxchar)
8596 maxchar = lo;
8597 PyUnicode_WRITE(kind, data, i, lo);
8598 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 else if (ch > maxchar)
8601 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603
8604 if (touched)
8605 return maxchar;
8606 else
8607 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608}
8609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008611fixtitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8614 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8615 const int kind = PyUnicode_KIND(self);
8616 void *data = PyUnicode_DATA(self);
8617 Py_UCS4 maxchar = 0;
8618 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008619 int previous_is_cased;
8620
8621 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 if (len == 1) {
8623 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8624 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
8625 if (ti != ch) {
8626 PyUnicode_WRITE(kind, data, i, ti);
8627 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00008628 }
8629 else
8630 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008632 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 for(; i < len; ++i) {
8634 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8635 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00008636
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640 nu = Py_UNICODE_TOTITLE(ch);
8641
8642 if (nu > maxchar)
8643 maxchar = nu;
8644 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00008645
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 if (Py_UNICODE_ISLOWER(ch) ||
8647 Py_UNICODE_ISUPPER(ch) ||
8648 Py_UNICODE_ISTITLE(ch))
8649 previous_is_cased = 1;
8650 else
8651 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008654}
8655
Tim Peters8ce9f162004-08-27 01:49:32 +00008656PyObject *
8657PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008660 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00008662 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008663 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
8664 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00008665 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 Py_ssize_t sz, i, res_offset;
8667 Py_UCS4 maxchar = 0;
8668 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669
Tim Peters05eba1f2004-08-27 21:32:02 +00008670 fseq = PySequence_Fast(seq, "");
8671 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008672 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00008673 }
8674
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008675 /* NOTE: the following code can't call back into Python code,
8676 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00008677 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008678
Tim Peters05eba1f2004-08-27 21:32:02 +00008679 seqlen = PySequence_Fast_GET_SIZE(fseq);
8680 /* If empty sequence, return u"". */
8681 if (seqlen == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 res = PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008683 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00008684 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008685 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00008686 /* If singleton sequence with an exact Unicode, return that. */
8687 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 item = items[0];
8689 if (PyUnicode_CheckExact(item)) {
8690 Py_INCREF(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 res = item;
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 goto Done;
8693 }
Tim Peters8ce9f162004-08-27 01:49:32 +00008694 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008695 else {
8696 /* Set up sep and seplen */
8697 if (separator == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 /* fall back to a blank space separator */
8699 sep = PyUnicode_FromOrdinal(' ');
Victor Stinnere9a29352011-10-01 02:14:59 +02008700 if (!sep)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008701 goto onError;
Tim Peters05eba1f2004-08-27 21:32:02 +00008702 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008703 else {
8704 if (!PyUnicode_Check(separator)) {
8705 PyErr_Format(PyExc_TypeError,
8706 "separator: expected str instance,"
8707 " %.80s found",
8708 Py_TYPE(separator)->tp_name);
8709 goto onError;
8710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 if (PyUnicode_READY(separator) == -1)
8712 goto onError;
8713 sep = separator;
8714 seplen = PyUnicode_GET_LENGTH(separator);
8715 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
8716 /* inc refcount to keep this code path symetric with the
8717 above case of a blank separator */
8718 Py_INCREF(sep);
Tim Peters05eba1f2004-08-27 21:32:02 +00008719 }
8720 }
8721
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008722 /* There are at least two things to join, or else we have a subclass
8723 * of str in the sequence.
8724 * Do a pre-pass to figure out the total amount of space we'll
8725 * need (sz), and see whether all argument are strings.
8726 */
8727 sz = 0;
8728 for (i = 0; i < seqlen; i++) {
8729 const Py_ssize_t old_sz = sz;
8730 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008731 if (!PyUnicode_Check(item)) {
8732 PyErr_Format(PyExc_TypeError,
8733 "sequence item %zd: expected str instance,"
8734 " %.80s found",
8735 i, Py_TYPE(item)->tp_name);
8736 goto onError;
8737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 if (PyUnicode_READY(item) == -1)
8739 goto onError;
8740 sz += PyUnicode_GET_LENGTH(item);
8741 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
8742 if (item_maxchar > maxchar)
8743 maxchar = item_maxchar;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008744 if (i != 0)
8745 sz += seplen;
8746 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
8747 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008749 goto onError;
8750 }
8751 }
Tim Petersced69f82003-09-16 20:30:58 +00008752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008754 if (res == NULL)
8755 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00008756
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008757 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008759 Py_ssize_t itemlen;
8760 item = items[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761 itemlen = PyUnicode_GET_LENGTH(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 /* Copy item, and maybe the separator. */
8763 if (i) {
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008764 if (PyUnicode_CopyCharacters(res, res_offset,
8765 sep, 0, seplen) < 0)
8766 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 res_offset += seplen;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008769 if (PyUnicode_CopyCharacters(res, res_offset,
8770 item, 0, itemlen) < 0)
8771 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 res_offset += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00008773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008774 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00008775
Benjamin Peterson29060642009-01-31 22:14:21 +00008776 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00008777 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 Py_XDECREF(sep);
8779 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008780
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00008782 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00008784 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008785 return NULL;
8786}
8787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008788#define FILL(kind, data, value, start, length) \
8789 do { \
8790 Py_ssize_t i_ = 0; \
8791 assert(kind != PyUnicode_WCHAR_KIND); \
8792 switch ((kind)) { \
8793 case PyUnicode_1BYTE_KIND: { \
8794 unsigned char * to_ = (unsigned char *)((data)) + (start); \
8795 memset(to_, (unsigned char)value, length); \
8796 break; \
8797 } \
8798 case PyUnicode_2BYTE_KIND: { \
8799 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
8800 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8801 break; \
8802 } \
8803 default: { \
8804 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
8805 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8806 break; \
8807 } \
8808 } \
8809 } while (0)
8810
Alexander Belopolsky40018472011-02-26 01:02:56 +00008811static PyUnicodeObject *
8812pad(PyUnicodeObject *self,
8813 Py_ssize_t left,
8814 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008815 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008816{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817 PyObject *u;
8818 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008819 int kind;
8820 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008821
8822 if (left < 0)
8823 left = 0;
8824 if (right < 0)
8825 right = 0;
8826
Tim Peters7a29bd52001-09-12 03:03:31 +00008827 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008828 Py_INCREF(self);
8829 return self;
8830 }
8831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
8833 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00008834 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
8835 return NULL;
8836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008837 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8838 if (fill > maxchar)
8839 maxchar = fill;
8840 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008841 if (!u)
8842 return NULL;
8843
8844 kind = PyUnicode_KIND(u);
8845 data = PyUnicode_DATA(u);
8846 if (left)
8847 FILL(kind, data, fill, 0, left);
8848 if (right)
8849 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinner157f83f2011-09-28 21:41:31 +02008850 if (PyUnicode_CopyCharacters(u, left,
8851 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008852 _PyUnicode_LENGTH(self)) < 0)
8853 {
8854 Py_DECREF(u);
8855 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008856 }
8857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008858 return (PyUnicodeObject*)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008859}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00008861
Alexander Belopolsky40018472011-02-26 01:02:56 +00008862PyObject *
8863PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008864{
Guido van Rossumd57fd912000-03-10 22:53:23 +00008865 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008866
8867 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008869 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008870
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 switch(PyUnicode_KIND(string)) {
8872 case PyUnicode_1BYTE_KIND:
8873 list = ucs1lib_splitlines(
8874 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
8875 PyUnicode_GET_LENGTH(string), keepends);
8876 break;
8877 case PyUnicode_2BYTE_KIND:
8878 list = ucs2lib_splitlines(
8879 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
8880 PyUnicode_GET_LENGTH(string), keepends);
8881 break;
8882 case PyUnicode_4BYTE_KIND:
8883 list = ucs4lib_splitlines(
8884 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
8885 PyUnicode_GET_LENGTH(string), keepends);
8886 break;
8887 default:
8888 assert(0);
8889 list = 0;
8890 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008891 Py_DECREF(string);
8892 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008893}
8894
Alexander Belopolsky40018472011-02-26 01:02:56 +00008895static PyObject *
8896split(PyUnicodeObject *self,
8897 PyUnicodeObject *substring,
8898 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008899{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 int kind1, kind2, kind;
8901 void *buf1, *buf2;
8902 Py_ssize_t len1, len2;
8903 PyObject* out;
8904
Guido van Rossumd57fd912000-03-10 22:53:23 +00008905 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008906 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908 if (PyUnicode_READY(self) == -1)
8909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911 if (substring == NULL)
8912 switch(PyUnicode_KIND(self)) {
8913 case PyUnicode_1BYTE_KIND:
8914 return ucs1lib_split_whitespace(
8915 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8916 PyUnicode_GET_LENGTH(self), maxcount
8917 );
8918 case PyUnicode_2BYTE_KIND:
8919 return ucs2lib_split_whitespace(
8920 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
8921 PyUnicode_GET_LENGTH(self), maxcount
8922 );
8923 case PyUnicode_4BYTE_KIND:
8924 return ucs4lib_split_whitespace(
8925 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
8926 PyUnicode_GET_LENGTH(self), maxcount
8927 );
8928 default:
8929 assert(0);
8930 return NULL;
8931 }
8932
8933 if (PyUnicode_READY(substring) == -1)
8934 return NULL;
8935
8936 kind1 = PyUnicode_KIND(self);
8937 kind2 = PyUnicode_KIND(substring);
8938 kind = kind1 > kind2 ? kind1 : kind2;
8939 buf1 = PyUnicode_DATA(self);
8940 buf2 = PyUnicode_DATA(substring);
8941 if (kind1 != kind)
8942 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
8943 if (!buf1)
8944 return NULL;
8945 if (kind2 != kind)
8946 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
8947 if (!buf2) {
8948 if (kind1 != kind) PyMem_Free(buf1);
8949 return NULL;
8950 }
8951 len1 = PyUnicode_GET_LENGTH(self);
8952 len2 = PyUnicode_GET_LENGTH(substring);
8953
8954 switch(kind) {
8955 case PyUnicode_1BYTE_KIND:
8956 out = ucs1lib_split(
8957 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8958 break;
8959 case PyUnicode_2BYTE_KIND:
8960 out = ucs2lib_split(
8961 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8962 break;
8963 case PyUnicode_4BYTE_KIND:
8964 out = ucs4lib_split(
8965 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
8966 break;
8967 default:
8968 out = NULL;
8969 }
8970 if (kind1 != kind)
8971 PyMem_Free(buf1);
8972 if (kind2 != kind)
8973 PyMem_Free(buf2);
8974 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008975}
8976
Alexander Belopolsky40018472011-02-26 01:02:56 +00008977static PyObject *
8978rsplit(PyUnicodeObject *self,
8979 PyUnicodeObject *substring,
8980 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 int kind1, kind2, kind;
8983 void *buf1, *buf2;
8984 Py_ssize_t len1, len2;
8985 PyObject* out;
8986
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008987 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008988 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008990 if (PyUnicode_READY(self) == -1)
8991 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00008992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008993 if (substring == NULL)
8994 switch(PyUnicode_KIND(self)) {
8995 case PyUnicode_1BYTE_KIND:
8996 return ucs1lib_rsplit_whitespace(
8997 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
8998 PyUnicode_GET_LENGTH(self), maxcount
8999 );
9000 case PyUnicode_2BYTE_KIND:
9001 return ucs2lib_rsplit_whitespace(
9002 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9003 PyUnicode_GET_LENGTH(self), maxcount
9004 );
9005 case PyUnicode_4BYTE_KIND:
9006 return ucs4lib_rsplit_whitespace(
9007 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9008 PyUnicode_GET_LENGTH(self), maxcount
9009 );
9010 default:
9011 assert(0);
9012 return NULL;
9013 }
9014
9015 if (PyUnicode_READY(substring) == -1)
9016 return NULL;
9017
9018 kind1 = PyUnicode_KIND(self);
9019 kind2 = PyUnicode_KIND(substring);
9020 kind = kind1 > kind2 ? kind1 : kind2;
9021 buf1 = PyUnicode_DATA(self);
9022 buf2 = PyUnicode_DATA(substring);
9023 if (kind1 != kind)
9024 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9025 if (!buf1)
9026 return NULL;
9027 if (kind2 != kind)
9028 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9029 if (!buf2) {
9030 if (kind1 != kind) PyMem_Free(buf1);
9031 return NULL;
9032 }
9033 len1 = PyUnicode_GET_LENGTH(self);
9034 len2 = PyUnicode_GET_LENGTH(substring);
9035
9036 switch(kind) {
9037 case PyUnicode_1BYTE_KIND:
9038 out = ucs1lib_rsplit(
9039 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9040 break;
9041 case PyUnicode_2BYTE_KIND:
9042 out = ucs2lib_rsplit(
9043 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9044 break;
9045 case PyUnicode_4BYTE_KIND:
9046 out = ucs4lib_rsplit(
9047 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9048 break;
9049 default:
9050 out = NULL;
9051 }
9052 if (kind1 != kind)
9053 PyMem_Free(buf1);
9054 if (kind2 != kind)
9055 PyMem_Free(buf2);
9056 return out;
9057}
9058
9059static Py_ssize_t
9060anylib_find(int kind, void *buf1, Py_ssize_t len1,
9061 void *buf2, Py_ssize_t len2, Py_ssize_t offset)
9062{
9063 switch(kind) {
9064 case PyUnicode_1BYTE_KIND:
9065 return ucs1lib_find(buf1, len1, buf2, len2, offset);
9066 case PyUnicode_2BYTE_KIND:
9067 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9068 case PyUnicode_4BYTE_KIND:
9069 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9070 }
9071 assert(0);
9072 return -1;
9073}
9074
9075static Py_ssize_t
9076anylib_count(int kind, void* sbuf, Py_ssize_t slen,
9077 void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
9078{
9079 switch(kind) {
9080 case PyUnicode_1BYTE_KIND:
9081 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9082 case PyUnicode_2BYTE_KIND:
9083 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9084 case PyUnicode_4BYTE_KIND:
9085 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9086 }
9087 assert(0);
9088 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009089}
9090
Alexander Belopolsky40018472011-02-26 01:02:56 +00009091static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092replace(PyObject *self, PyObject *str1,
9093 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009094{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 PyObject *u;
9096 char *sbuf = PyUnicode_DATA(self);
9097 char *buf1 = PyUnicode_DATA(str1);
9098 char *buf2 = PyUnicode_DATA(str2);
9099 int srelease = 0, release1 = 0, release2 = 0;
9100 int skind = PyUnicode_KIND(self);
9101 int kind1 = PyUnicode_KIND(str1);
9102 int kind2 = PyUnicode_KIND(str2);
9103 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9104 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9105 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009106
9107 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009108 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009110 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 if (skind < kind1)
9113 /* substring too wide to be present */
9114 goto nothing;
9115
9116 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009117 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009118 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009120 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009122 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009123 Py_UCS4 u1, u2, maxchar;
9124 int mayshrink, rkind;
9125 u1 = PyUnicode_READ_CHAR(str1, 0);
9126 if (!findchar(sbuf, PyUnicode_KIND(self),
9127 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009128 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009129 u2 = PyUnicode_READ_CHAR(str2, 0);
9130 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9131 /* Replacing u1 with u2 may cause a maxchar reduction in the
9132 result string. */
9133 mayshrink = maxchar > 127;
9134 if (u2 > maxchar) {
9135 maxchar = u2;
9136 mayshrink = 0;
9137 }
9138 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009139 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 goto error;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009141 if (PyUnicode_CopyCharacters(u, 0,
9142 (PyObject*)self, 0, slen) < 0)
9143 {
9144 Py_DECREF(u);
9145 return NULL;
9146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 rkind = PyUnicode_KIND(u);
9148 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9149 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009150 if (--maxcount < 0)
9151 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009153 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009154 if (mayshrink) {
9155 PyObject *tmp = u;
9156 u = PyUnicode_FromKindAndData(rkind, PyUnicode_DATA(tmp),
9157 PyUnicode_GET_LENGTH(tmp));
9158 Py_DECREF(tmp);
9159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 int rkind = skind;
9162 char *res;
9163 if (kind1 < rkind) {
9164 /* widen substring */
9165 buf1 = _PyUnicode_AsKind(str1, rkind);
9166 if (!buf1) goto error;
9167 release1 = 1;
9168 }
9169 i = anylib_find(rkind, sbuf, slen, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009170 if (i < 0)
9171 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009172 if (rkind > kind2) {
9173 /* widen replacement */
9174 buf2 = _PyUnicode_AsKind(str2, rkind);
9175 if (!buf2) goto error;
9176 release2 = 1;
9177 }
9178 else if (rkind < kind2) {
9179 /* widen self and buf1 */
9180 rkind = kind2;
9181 if (release1) PyMem_Free(buf1);
9182 sbuf = _PyUnicode_AsKind(self, rkind);
9183 if (!sbuf) goto error;
9184 srelease = 1;
9185 buf1 = _PyUnicode_AsKind(str1, rkind);
9186 if (!buf1) goto error;
9187 release1 = 1;
9188 }
9189 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, slen));
9190 if (!res) {
9191 PyErr_NoMemory();
9192 goto error;
9193 }
9194 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009195 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9197 buf2,
9198 PyUnicode_KIND_SIZE(rkind, len2));
9199 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009200
9201 while ( --maxcount > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 i = anylib_find(rkind, sbuf+PyUnicode_KIND_SIZE(rkind, i),
9203 slen-i,
9204 buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009205 if (i == -1)
9206 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9208 buf2,
9209 PyUnicode_KIND_SIZE(rkind, len2));
9210 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009211 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212
9213 u = PyUnicode_FromKindAndData(rkind, res, slen);
9214 PyMem_Free(res);
9215 if (!u) goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009216 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 Py_ssize_t n, i, j, ires;
9220 Py_ssize_t product, new_size;
9221 int rkind = skind;
9222 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 if (kind1 < rkind) {
9225 buf1 = _PyUnicode_AsKind(str1, rkind);
9226 if (!buf1) goto error;
9227 release1 = 1;
9228 }
9229 n = anylib_count(rkind, sbuf, slen, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009230 if (n == 0)
9231 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 if (kind2 < rkind) {
9233 buf2 = _PyUnicode_AsKind(str2, rkind);
9234 if (!buf2) goto error;
9235 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 else if (kind2 > rkind) {
9238 rkind = kind2;
9239 sbuf = _PyUnicode_AsKind(self, rkind);
9240 if (!sbuf) goto error;
9241 srelease = 1;
9242 if (release1) PyMem_Free(buf1);
9243 buf1 = _PyUnicode_AsKind(str1, rkind);
9244 if (!buf1) goto error;
9245 release1 = 1;
9246 }
9247 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9248 PyUnicode_GET_LENGTH(str1))); */
9249 product = n * (len2-len1);
9250 if ((product / (len2-len1)) != n) {
9251 PyErr_SetString(PyExc_OverflowError,
9252 "replace string is too long");
9253 goto error;
9254 }
9255 new_size = slen + product;
9256 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9257 PyErr_SetString(PyExc_OverflowError,
9258 "replace string is too long");
9259 goto error;
9260 }
9261 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, new_size));
9262 if (!res)
9263 goto error;
9264 ires = i = 0;
9265 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009266 while (n-- > 0) {
9267 /* look for next match */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 j = anylib_find(rkind,
9269 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9270 slen-i, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009271 if (j == -1)
9272 break;
9273 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009274 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9276 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9277 PyUnicode_KIND_SIZE(rkind, j-i));
9278 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009279 }
9280 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 if (len2 > 0) {
9282 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9283 buf2,
9284 PyUnicode_KIND_SIZE(rkind, len2));
9285 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009289 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009290 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009291 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9292 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9293 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009294 } else {
9295 /* interleave */
9296 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9298 buf2,
9299 PyUnicode_KIND_SIZE(rkind, len2));
9300 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009301 if (--n <= 0)
9302 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9304 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9305 PyUnicode_KIND_SIZE(rkind, 1));
9306 ires++;
9307 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9310 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9311 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009313 u = PyUnicode_FromKindAndData(rkind, res, new_size);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02009314 PyMem_Free(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009315 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 if (srelease)
9317 PyMem_FREE(sbuf);
9318 if (release1)
9319 PyMem_FREE(buf1);
9320 if (release2)
9321 PyMem_FREE(buf2);
9322 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009323
Benjamin Peterson29060642009-01-31 22:14:21 +00009324 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009325 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 if (srelease)
9327 PyMem_FREE(sbuf);
9328 if (release1)
9329 PyMem_FREE(buf1);
9330 if (release2)
9331 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009332 if (PyUnicode_CheckExact(self)) {
9333 Py_INCREF(self);
9334 return (PyObject *) self;
9335 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009336 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 error:
9338 if (srelease && sbuf)
9339 PyMem_FREE(sbuf);
9340 if (release1 && buf1)
9341 PyMem_FREE(buf1);
9342 if (release2 && buf2)
9343 PyMem_FREE(buf2);
9344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345}
9346
9347/* --- Unicode Object Methods --------------------------------------------- */
9348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009349PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009350 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351\n\
9352Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009353characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009354
9355static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009356unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009358 return fixup(self, fixtitle);
9359}
9360
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009361PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009362 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363\n\
9364Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009365have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009366
9367static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009368unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370 return fixup(self, fixcapitalize);
9371}
9372
9373#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009374PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009375 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376\n\
9377Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009378normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379
9380static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009381unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382{
9383 PyObject *list;
9384 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009385 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387 /* Split into words */
9388 list = split(self, NULL, -1);
9389 if (!list)
9390 return NULL;
9391
9392 /* Capitalize each word */
9393 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9394 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009395 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396 if (item == NULL)
9397 goto onError;
9398 Py_DECREF(PyList_GET_ITEM(list, i));
9399 PyList_SET_ITEM(list, i, item);
9400 }
9401
9402 /* Join the words to form a new string */
9403 item = PyUnicode_Join(NULL, list);
9404
Benjamin Peterson29060642009-01-31 22:14:21 +00009405 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406 Py_DECREF(list);
9407 return (PyObject *)item;
9408}
9409#endif
9410
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009411/* Argument converter. Coerces to a single unicode character */
9412
9413static int
9414convert_uc(PyObject *obj, void *addr)
9415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009417 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009418
Benjamin Peterson14339b62009-01-31 16:36:08 +00009419 uniobj = PyUnicode_FromObject(obj);
9420 if (uniobj == NULL) {
9421 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009422 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009423 return 0;
9424 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009426 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009427 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009428 Py_DECREF(uniobj);
9429 return 0;
9430 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009432 Py_DECREF(uniobj);
9433 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009434}
9435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009436PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009437 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009438\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009439Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009440done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441
9442static PyObject *
9443unicode_center(PyUnicodeObject *self, PyObject *args)
9444{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009445 Py_ssize_t marg, left;
9446 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 Py_UCS4 fillchar = ' ';
9448
Victor Stinnere9a29352011-10-01 02:14:59 +02009449 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451
Victor Stinnere9a29352011-10-01 02:14:59 +02009452 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009453 return NULL;
9454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456 Py_INCREF(self);
9457 return (PyObject*) self;
9458 }
9459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461 left = marg / 2 + (marg & width & 1);
9462
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009463 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464}
9465
Marc-André Lemburge5034372000-08-08 08:04:29 +00009466#if 0
9467
9468/* This code should go into some future Unicode collation support
9469 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009470 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009471
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009472/* speedy UTF-16 code point order comparison */
9473/* gleaned from: */
9474/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9475
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009476static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009477{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009478 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009479 0, 0, 0, 0, 0, 0, 0, 0,
9480 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009481 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009482};
9483
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484static int
9485unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9486{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009487 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009488
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 Py_UNICODE *s1 = str1->str;
9490 Py_UNICODE *s2 = str2->str;
9491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 len1 = str1->_base._base.length;
9493 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +00009494
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00009496 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009497
9498 c1 = *s1++;
9499 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00009500
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 if (c1 > (1<<11) * 26)
9502 c1 += utf16Fixup[c1>>11];
9503 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009504 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009505 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00009506
9507 if (c1 != c2)
9508 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00009509
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009510 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 }
9512
9513 return (len1 < len2) ? -1 : (len1 != len2);
9514}
9515
Marc-André Lemburge5034372000-08-08 08:04:29 +00009516#else
9517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518/* This function assumes that str1 and str2 are readied by the caller. */
9519
Marc-André Lemburge5034372000-08-08 08:04:29 +00009520static int
9521unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9522{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 int kind1, kind2;
9524 void *data1, *data2;
9525 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 kind1 = PyUnicode_KIND(str1);
9528 kind2 = PyUnicode_KIND(str2);
9529 data1 = PyUnicode_DATA(str1);
9530 data2 = PyUnicode_DATA(str2);
9531 len1 = PyUnicode_GET_LENGTH(str1);
9532 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +00009533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 for (i = 0; i < len1 && i < len2; ++i) {
9535 Py_UCS4 c1, c2;
9536 c1 = PyUnicode_READ(kind1, data1, i);
9537 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +00009538
9539 if (c1 != c2)
9540 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009541 }
9542
9543 return (len1 < len2) ? -1 : (len1 != len2);
9544}
9545
9546#endif
9547
Alexander Belopolsky40018472011-02-26 01:02:56 +00009548int
9549PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9552 if (PyUnicode_READY(left) == -1 ||
9553 PyUnicode_READY(right) == -1)
9554 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009555 return unicode_compare((PyUnicodeObject *)left,
9556 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009558 PyErr_Format(PyExc_TypeError,
9559 "Can't compare %.100s and %.100s",
9560 left->ob_type->tp_name,
9561 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009562 return -1;
9563}
9564
Martin v. Löwis5b222132007-06-10 09:51:05 +00009565int
9566PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
9567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 Py_ssize_t i;
9569 int kind;
9570 void *data;
9571 Py_UCS4 chr;
9572
Martin v. Löwis5b222132007-06-10 09:51:05 +00009573 assert(PyUnicode_Check(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 if (PyUnicode_READY(uni) == -1)
9575 return -1;
9576 kind = PyUnicode_KIND(uni);
9577 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +00009578 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
9580 if (chr != str[i])
9581 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00009582 /* This check keeps Python strings that end in '\0' from comparing equal
9583 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +00009585 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009586 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00009587 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009588 return 0;
9589}
9590
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009591
Benjamin Peterson29060642009-01-31 22:14:21 +00009592#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00009593 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009594
Alexander Belopolsky40018472011-02-26 01:02:56 +00009595PyObject *
9596PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009597{
9598 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009599
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009600 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9601 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009602 if (PyUnicode_READY(left) == -1 ||
9603 PyUnicode_READY(right) == -1)
9604 return NULL;
9605 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
9606 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009607 if (op == Py_EQ) {
9608 Py_INCREF(Py_False);
9609 return Py_False;
9610 }
9611 if (op == Py_NE) {
9612 Py_INCREF(Py_True);
9613 return Py_True;
9614 }
9615 }
9616 if (left == right)
9617 result = 0;
9618 else
9619 result = unicode_compare((PyUnicodeObject *)left,
9620 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009621
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009622 /* Convert the return value to a Boolean */
9623 switch (op) {
9624 case Py_EQ:
9625 v = TEST_COND(result == 0);
9626 break;
9627 case Py_NE:
9628 v = TEST_COND(result != 0);
9629 break;
9630 case Py_LE:
9631 v = TEST_COND(result <= 0);
9632 break;
9633 case Py_GE:
9634 v = TEST_COND(result >= 0);
9635 break;
9636 case Py_LT:
9637 v = TEST_COND(result == -1);
9638 break;
9639 case Py_GT:
9640 v = TEST_COND(result == 1);
9641 break;
9642 default:
9643 PyErr_BadArgument();
9644 return NULL;
9645 }
9646 Py_INCREF(v);
9647 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009649
Brian Curtindfc80e32011-08-10 20:28:54 -05009650 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009651}
9652
Alexander Belopolsky40018472011-02-26 01:02:56 +00009653int
9654PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00009655{
Thomas Wouters477c8d52006-05-27 19:21:47 +00009656 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 int kind1, kind2, kind;
9658 void *buf1, *buf2;
9659 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009660 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009661
9662 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00009663 sub = PyUnicode_FromObject(element);
9664 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009665 PyErr_Format(PyExc_TypeError,
9666 "'in <string>' requires string as left operand, not %s",
9667 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009668 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 if (PyUnicode_READY(sub) == -1)
9671 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009672
Thomas Wouters477c8d52006-05-27 19:21:47 +00009673 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +02009674 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009675 Py_DECREF(sub);
9676 return -1;
9677 }
9678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009679 kind1 = PyUnicode_KIND(str);
9680 kind2 = PyUnicode_KIND(sub);
9681 kind = kind1 > kind2 ? kind1 : kind2;
9682 buf1 = PyUnicode_DATA(str);
9683 buf2 = PyUnicode_DATA(sub);
9684 if (kind1 != kind)
9685 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
9686 if (!buf1) {
9687 Py_DECREF(sub);
9688 return -1;
9689 }
9690 if (kind2 != kind)
9691 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
9692 if (!buf2) {
9693 Py_DECREF(sub);
9694 if (kind1 != kind) PyMem_Free(buf1);
9695 return -1;
9696 }
9697 len1 = PyUnicode_GET_LENGTH(str);
9698 len2 = PyUnicode_GET_LENGTH(sub);
9699
9700 switch(kind) {
9701 case PyUnicode_1BYTE_KIND:
9702 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
9703 break;
9704 case PyUnicode_2BYTE_KIND:
9705 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
9706 break;
9707 case PyUnicode_4BYTE_KIND:
9708 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
9709 break;
9710 default:
9711 result = -1;
9712 assert(0);
9713 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009714
9715 Py_DECREF(str);
9716 Py_DECREF(sub);
9717
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009718 if (kind1 != kind)
9719 PyMem_Free(buf1);
9720 if (kind2 != kind)
9721 PyMem_Free(buf2);
9722
Guido van Rossum403d68b2000-03-13 15:55:09 +00009723 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009724}
9725
Guido van Rossumd57fd912000-03-10 22:53:23 +00009726/* Concat to string or Unicode object giving a new Unicode object. */
9727
Alexander Belopolsky40018472011-02-26 01:02:56 +00009728PyObject *
9729PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731 PyObject *u = NULL, *v = NULL, *w;
9732 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009733
9734 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009736 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009737 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009738 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009739 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009740 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741
9742 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +02009743 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009744 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746 }
Victor Stinnera464fc12011-10-02 20:39:30 +02009747 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009748 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750 }
9751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009752 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +02009753 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009754
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 w = PyUnicode_New(
9757 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
9758 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 goto onError;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009761 if (PyUnicode_CopyCharacters(w, 0, u, 0, PyUnicode_GET_LENGTH(u)) < 0)
9762 goto onError;
Victor Stinner157f83f2011-09-28 21:41:31 +02009763 if (PyUnicode_CopyCharacters(w, PyUnicode_GET_LENGTH(u),
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009764 v, 0,
9765 PyUnicode_GET_LENGTH(v)) < 0)
9766 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009767 Py_DECREF(u);
9768 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009769 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009770
Benjamin Peterson29060642009-01-31 22:14:21 +00009771 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772 Py_XDECREF(u);
9773 Py_XDECREF(v);
9774 return NULL;
9775}
9776
Walter Dörwald1ab83302007-05-18 17:15:44 +00009777void
Victor Stinner23e56682011-10-03 03:54:37 +02009778PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +00009779{
Victor Stinner23e56682011-10-03 03:54:37 +02009780 PyObject *left, *res;
9781
9782 if (p_left == NULL) {
9783 if (!PyErr_Occurred())
9784 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +00009785 return;
9786 }
Victor Stinner23e56682011-10-03 03:54:37 +02009787 left = *p_left;
9788 if (right == NULL || !PyUnicode_Check(left)) {
9789 if (!PyErr_Occurred())
9790 PyErr_BadInternalCall();
9791 goto error;
9792 }
9793
9794 if (PyUnicode_CheckExact(left) && left != unicode_empty
9795 && PyUnicode_CheckExact(right) && right != unicode_empty
9796 && unicode_resizable(left)
9797 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
9798 || _PyUnicode_WSTR(left) != NULL))
9799 {
9800 Py_ssize_t u_len, v_len, new_len, copied;
9801
9802 /* FIXME: don't make wstr string ready */
9803 if (PyUnicode_READY(left))
9804 goto error;
9805 if (PyUnicode_READY(right))
9806 goto error;
9807
9808 /* FIXME: support ascii+latin1, PyASCIIObject => PyCompactUnicodeObject */
9809 if (PyUnicode_MAX_CHAR_VALUE(right) <= PyUnicode_MAX_CHAR_VALUE(left))
9810 {
9811 u_len = PyUnicode_GET_LENGTH(left);
9812 v_len = PyUnicode_GET_LENGTH(right);
9813 if (u_len > PY_SSIZE_T_MAX - v_len) {
9814 PyErr_SetString(PyExc_OverflowError,
9815 "strings are too large to concat");
9816 goto error;
9817 }
9818 new_len = u_len + v_len;
9819
9820 /* Now we own the last reference to 'left', so we can resize it
9821 * in-place.
9822 */
9823 if (unicode_resize(&left, new_len) != 0) {
9824 /* XXX if _PyUnicode_Resize() fails, 'left' has been
9825 * deallocated so it cannot be put back into
9826 * 'variable'. The MemoryError is raised when there
9827 * is no value in 'variable', which might (very
9828 * remotely) be a cause of incompatibilities.
9829 */
9830 goto error;
9831 }
9832 /* copy 'right' into the newly allocated area of 'left' */
9833 copied = PyUnicode_CopyCharacters(left, u_len,
9834 right, 0,
9835 v_len);
9836 assert(0 <= copied);
9837 *p_left = left;
9838 return;
9839 }
9840 }
9841
9842 res = PyUnicode_Concat(left, right);
9843 if (res == NULL)
9844 goto error;
9845 Py_DECREF(left);
9846 *p_left = res;
9847 return;
9848
9849error:
9850 Py_DECREF(*p_left);
9851 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00009852}
9853
9854void
9855PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
9856{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009857 PyUnicode_Append(pleft, right);
9858 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00009859}
9860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009861PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009862 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009863\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00009864Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009865string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009866interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009867
9868static PyObject *
9869unicode_count(PyUnicodeObject *self, PyObject *args)
9870{
9871 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009872 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009873 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 int kind1, kind2, kind;
9876 void *buf1, *buf2;
9877 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009878
Jesus Ceaac451502011-04-20 17:09:23 +02009879 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
9880 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +00009881 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +00009882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 kind1 = PyUnicode_KIND(self);
9884 kind2 = PyUnicode_KIND(substring);
9885 kind = kind1 > kind2 ? kind1 : kind2;
9886 buf1 = PyUnicode_DATA(self);
9887 buf2 = PyUnicode_DATA(substring);
9888 if (kind1 != kind)
9889 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9890 if (!buf1) {
9891 Py_DECREF(substring);
9892 return NULL;
9893 }
9894 if (kind2 != kind)
9895 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9896 if (!buf2) {
9897 Py_DECREF(substring);
9898 if (kind1 != kind) PyMem_Free(buf1);
9899 return NULL;
9900 }
9901 len1 = PyUnicode_GET_LENGTH(self);
9902 len2 = PyUnicode_GET_LENGTH(substring);
9903
9904 ADJUST_INDICES(start, end, len1);
9905 switch(kind) {
9906 case PyUnicode_1BYTE_KIND:
9907 iresult = ucs1lib_count(
9908 ((Py_UCS1*)buf1) + start, end - start,
9909 buf2, len2, PY_SSIZE_T_MAX
9910 );
9911 break;
9912 case PyUnicode_2BYTE_KIND:
9913 iresult = ucs2lib_count(
9914 ((Py_UCS2*)buf1) + start, end - start,
9915 buf2, len2, PY_SSIZE_T_MAX
9916 );
9917 break;
9918 case PyUnicode_4BYTE_KIND:
9919 iresult = ucs4lib_count(
9920 ((Py_UCS4*)buf1) + start, end - start,
9921 buf2, len2, PY_SSIZE_T_MAX
9922 );
9923 break;
9924 default:
9925 assert(0); iresult = 0;
9926 }
9927
9928 result = PyLong_FromSsize_t(iresult);
9929
9930 if (kind1 != kind)
9931 PyMem_Free(buf1);
9932 if (kind2 != kind)
9933 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934
9935 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009936
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937 return result;
9938}
9939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009940PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +00009941 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009942\n\
Victor Stinnere14e2122010-11-07 18:41:46 +00009943Encode S using the codec registered for encoding. Default encoding\n\
9944is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +00009945handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009946a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
9947'xmlcharrefreplace' as well as any other name registered with\n\
9948codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009949
9950static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +00009951unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952{
Benjamin Peterson308d6372009-09-18 21:42:35 +00009953 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +00009954 char *encoding = NULL;
9955 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +00009956
Benjamin Peterson308d6372009-09-18 21:42:35 +00009957 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
9958 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +00009960 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00009961}
9962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009963PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009964 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965\n\
9966Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009967If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968
9969static PyObject*
9970unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
9971{
9972 Py_UNICODE *e;
9973 Py_UNICODE *p;
9974 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009975 Py_UNICODE *qe;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 Py_ssize_t i, j, incr, wstr_length;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009977 PyUnicodeObject *u;
9978 int tabsize = 8;
9979
9980 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00009981 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 if (PyUnicode_AsUnicodeAndSize((PyObject *)self, &wstr_length) == NULL)
9984 return NULL;
9985
Thomas Wouters7e474022000-07-16 12:04:32 +00009986 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009987 i = 0; /* chars up to and including most recent \n or \r */
9988 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 e = _PyUnicode_WSTR(self) + wstr_length; /* end of input */
9990 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +00009992 if (tabsize > 0) {
9993 incr = tabsize - (j % tabsize); /* cannot overflow */
9994 if (j > PY_SSIZE_T_MAX - incr)
9995 goto overflow1;
9996 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00009997 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009998 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009999 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010000 if (j > PY_SSIZE_T_MAX - 1)
10001 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010002 j++;
10003 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010004 if (i > PY_SSIZE_T_MAX - j)
10005 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010006 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010007 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008 }
10009 }
10010
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010011 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +000010012 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010013
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014 /* Second pass: create output string and fill it */
10015 u = _PyUnicode_New(i + j);
10016 if (!u)
10017 return NULL;
10018
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010019 j = 0; /* same as in first pass */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 q = _PyUnicode_WSTR(u); /* next output char */
10021 qe = _PyUnicode_WSTR(u) + PyUnicode_GET_SIZE(u); /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010024 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010025 if (tabsize > 0) {
10026 i = tabsize - (j % tabsize);
10027 j += i;
10028 while (i--) {
10029 if (q >= qe)
10030 goto overflow2;
10031 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010032 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010033 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010034 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010035 else {
10036 if (q >= qe)
10037 goto overflow2;
10038 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010039 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040 if (*p == '\n' || *p == '\r')
10041 j = 0;
10042 }
10043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 if (PyUnicode_READY(u) == -1) {
10045 Py_DECREF(u);
10046 return NULL;
10047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010049
10050 overflow2:
10051 Py_DECREF(u);
10052 overflow1:
10053 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055}
10056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010057PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010058 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010059\n\
10060Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010061such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062arguments start and end are interpreted as in slice notation.\n\
10063\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010064Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010065
10066static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068{
Jesus Ceaac451502011-04-20 17:09:23 +020010069 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010070 Py_ssize_t start;
10071 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010072 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010073
Jesus Ceaac451502011-04-20 17:09:23 +020010074 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10075 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010076 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 if (PyUnicode_READY(self) == -1)
10079 return NULL;
10080 if (PyUnicode_READY(substring) == -1)
10081 return NULL;
10082
10083 result = any_find_slice(
10084 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10085 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010086 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087
10088 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 if (result == -2)
10091 return NULL;
10092
Christian Heimes217cfd12007-12-02 14:31:20 +000010093 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094}
10095
10096static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010097unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010099 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10100 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010101 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103}
10104
Guido van Rossumc2504932007-09-18 19:42:40 +000010105/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010106 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010107static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010108unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109{
Guido van Rossumc2504932007-09-18 19:42:40 +000010110 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010111 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 if (_PyUnicode_HASH(self) != -1)
10114 return _PyUnicode_HASH(self);
10115 if (PyUnicode_READY(self) == -1)
10116 return -1;
10117 len = PyUnicode_GET_LENGTH(self);
10118
10119 /* The hash function as a macro, gets expanded three times below. */
10120#define HASH(P) \
10121 x = (Py_uhash_t)*P << 7; \
10122 while (--len >= 0) \
10123 x = (1000003*x) ^ (Py_uhash_t)*P++;
10124
10125 switch (PyUnicode_KIND(self)) {
10126 case PyUnicode_1BYTE_KIND: {
10127 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10128 HASH(c);
10129 break;
10130 }
10131 case PyUnicode_2BYTE_KIND: {
10132 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10133 HASH(s);
10134 break;
10135 }
10136 default: {
10137 Py_UCS4 *l;
10138 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10139 "Impossible switch case in unicode_hash");
10140 l = PyUnicode_4BYTE_DATA(self);
10141 HASH(l);
10142 break;
10143 }
10144 }
10145 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10146
Guido van Rossumc2504932007-09-18 19:42:40 +000010147 if (x == -1)
10148 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010150 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010151}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010154PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010155 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010157Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158
10159static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010162 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010163 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010164 Py_ssize_t start;
10165 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010166
Jesus Ceaac451502011-04-20 17:09:23 +020010167 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10168 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 if (PyUnicode_READY(self) == -1)
10172 return NULL;
10173 if (PyUnicode_READY(substring) == -1)
10174 return NULL;
10175
10176 result = any_find_slice(
10177 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10178 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010179 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010180
10181 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 if (result == -2)
10184 return NULL;
10185
Guido van Rossumd57fd912000-03-10 22:53:23 +000010186 if (result < 0) {
10187 PyErr_SetString(PyExc_ValueError, "substring not found");
10188 return NULL;
10189 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010190
Christian Heimes217cfd12007-12-02 14:31:20 +000010191 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192}
10193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010194PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010195 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010196\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010197Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010198at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199
10200static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010201unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 Py_ssize_t i, length;
10204 int kind;
10205 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010206 int cased;
10207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 if (PyUnicode_READY(self) == -1)
10209 return NULL;
10210 length = PyUnicode_GET_LENGTH(self);
10211 kind = PyUnicode_KIND(self);
10212 data = PyUnicode_DATA(self);
10213
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 if (length == 1)
10216 return PyBool_FromLong(
10217 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010218
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010219 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010221 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010222
Guido van Rossumd57fd912000-03-10 22:53:23 +000010223 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 for (i = 0; i < length; i++) {
10225 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010226
Benjamin Peterson29060642009-01-31 22:14:21 +000010227 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10228 return PyBool_FromLong(0);
10229 else if (!cased && Py_UNICODE_ISLOWER(ch))
10230 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010231 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010232 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010233}
10234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010235PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010236 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010237\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010238Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010239at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010240
10241static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010242unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010243{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 Py_ssize_t i, length;
10245 int kind;
10246 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247 int cased;
10248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 if (PyUnicode_READY(self) == -1)
10250 return NULL;
10251 length = PyUnicode_GET_LENGTH(self);
10252 kind = PyUnicode_KIND(self);
10253 data = PyUnicode_DATA(self);
10254
Guido van Rossumd57fd912000-03-10 22:53:23 +000010255 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (length == 1)
10257 return PyBool_FromLong(
10258 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010259
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010260 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010262 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010263
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 for (i = 0; i < length; i++) {
10266 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010267
Benjamin Peterson29060642009-01-31 22:14:21 +000010268 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10269 return PyBool_FromLong(0);
10270 else if (!cased && Py_UNICODE_ISUPPER(ch))
10271 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010272 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010273 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274}
10275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010276PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010277 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010278\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010279Return True if S is a titlecased string and there is at least one\n\
10280character in S, i.e. upper- and titlecase characters may only\n\
10281follow uncased characters and lowercase characters only cased ones.\n\
10282Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283
10284static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010285unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 Py_ssize_t i, length;
10288 int kind;
10289 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290 int cased, previous_is_cased;
10291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 if (PyUnicode_READY(self) == -1)
10293 return NULL;
10294 length = PyUnicode_GET_LENGTH(self);
10295 kind = PyUnicode_KIND(self);
10296 data = PyUnicode_DATA(self);
10297
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 if (length == 1) {
10300 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10301 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10302 (Py_UNICODE_ISUPPER(ch) != 0));
10303 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010305 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010307 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010308
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309 cased = 0;
10310 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 for (i = 0; i < length; i++) {
10312 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010313
Benjamin Peterson29060642009-01-31 22:14:21 +000010314 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10315 if (previous_is_cased)
10316 return PyBool_FromLong(0);
10317 previous_is_cased = 1;
10318 cased = 1;
10319 }
10320 else if (Py_UNICODE_ISLOWER(ch)) {
10321 if (!previous_is_cased)
10322 return PyBool_FromLong(0);
10323 previous_is_cased = 1;
10324 cased = 1;
10325 }
10326 else
10327 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010329 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330}
10331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010332PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010333 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010334\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010335Return True if all characters in S are whitespace\n\
10336and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010337
10338static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010339unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010340{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 Py_ssize_t i, length;
10342 int kind;
10343 void *data;
10344
10345 if (PyUnicode_READY(self) == -1)
10346 return NULL;
10347 length = PyUnicode_GET_LENGTH(self);
10348 kind = PyUnicode_KIND(self);
10349 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010350
Guido van Rossumd57fd912000-03-10 22:53:23 +000010351 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 if (length == 1)
10353 return PyBool_FromLong(
10354 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010356 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010358 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 for (i = 0; i < length; i++) {
10361 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010362 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010363 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010365 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010366}
10367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010368PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010369 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010370\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010371Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010372and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010373
10374static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010375unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010376{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 Py_ssize_t i, length;
10378 int kind;
10379 void *data;
10380
10381 if (PyUnicode_READY(self) == -1)
10382 return NULL;
10383 length = PyUnicode_GET_LENGTH(self);
10384 kind = PyUnicode_KIND(self);
10385 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010386
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010387 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 if (length == 1)
10389 return PyBool_FromLong(
10390 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010391
10392 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010394 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 for (i = 0; i < length; i++) {
10397 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010398 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010399 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010400 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010401}
10402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010403PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010404 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010405\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010406Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010407and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010408
10409static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010410unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 int kind;
10413 void *data;
10414 Py_ssize_t len, i;
10415
10416 if (PyUnicode_READY(self) == -1)
10417 return NULL;
10418
10419 kind = PyUnicode_KIND(self);
10420 data = PyUnicode_DATA(self);
10421 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010422
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010423 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 if (len == 1) {
10425 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10426 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10427 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010428
10429 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010431 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 for (i = 0; i < len; i++) {
10434 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010435 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010436 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010437 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010438 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010439}
10440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010441PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010442 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010444Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010445False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010446
10447static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010448unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 Py_ssize_t i, length;
10451 int kind;
10452 void *data;
10453
10454 if (PyUnicode_READY(self) == -1)
10455 return NULL;
10456 length = PyUnicode_GET_LENGTH(self);
10457 kind = PyUnicode_KIND(self);
10458 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 if (length == 1)
10462 return PyBool_FromLong(
10463 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010464
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010465 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010467 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 for (i = 0; i < length; i++) {
10470 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010471 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010473 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474}
10475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010476PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010477 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010478\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010479Return True if all characters in S are digits\n\
10480and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481
10482static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010483unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 Py_ssize_t i, length;
10486 int kind;
10487 void *data;
10488
10489 if (PyUnicode_READY(self) == -1)
10490 return NULL;
10491 length = PyUnicode_GET_LENGTH(self);
10492 kind = PyUnicode_KIND(self);
10493 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494
Guido van Rossumd57fd912000-03-10 22:53:23 +000010495 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 if (length == 1) {
10497 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10498 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
10499 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010500
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010501 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010504
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 for (i = 0; i < length; i++) {
10506 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010507 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010509 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510}
10511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010513 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010515Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010516False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517
10518static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010519unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 Py_ssize_t i, length;
10522 int kind;
10523 void *data;
10524
10525 if (PyUnicode_READY(self) == -1)
10526 return NULL;
10527 length = PyUnicode_GET_LENGTH(self);
10528 kind = PyUnicode_KIND(self);
10529 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 if (length == 1)
10533 return PyBool_FromLong(
10534 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010536 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010538 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 for (i = 0; i < length; i++) {
10541 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010544 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545}
10546
Martin v. Löwis47383402007-08-15 07:32:56 +000010547int
10548PyUnicode_IsIdentifier(PyObject *self)
10549{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 int kind;
10551 void *data;
10552 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010553 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000010554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (PyUnicode_READY(self) == -1) {
10556 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000010557 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 }
10559
10560 /* Special case for empty strings */
10561 if (PyUnicode_GET_LENGTH(self) == 0)
10562 return 0;
10563 kind = PyUnicode_KIND(self);
10564 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000010565
10566 /* PEP 3131 says that the first character must be in
10567 XID_Start and subsequent characters in XID_Continue,
10568 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000010570 letters, digits, underscore). However, given the current
10571 definition of XID_Start and XID_Continue, it is sufficient
10572 to check just for these, except that _ must be allowed
10573 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050010575 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000010576 return 0;
10577
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040010578 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000010581 return 1;
10582}
10583
10584PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010585 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000010586\n\
10587Return True if S is a valid identifier according\n\
10588to the language definition.");
10589
10590static PyObject*
10591unicode_isidentifier(PyObject *self)
10592{
10593 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
10594}
10595
Georg Brandl559e5d72008-06-11 18:37:52 +000010596PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010597 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000010598\n\
10599Return True if all characters in S are considered\n\
10600printable in repr() or S is empty, False otherwise.");
10601
10602static PyObject*
10603unicode_isprintable(PyObject *self)
10604{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 Py_ssize_t i, length;
10606 int kind;
10607 void *data;
10608
10609 if (PyUnicode_READY(self) == -1)
10610 return NULL;
10611 length = PyUnicode_GET_LENGTH(self);
10612 kind = PyUnicode_KIND(self);
10613 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000010614
10615 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 if (length == 1)
10617 return PyBool_FromLong(
10618 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000010619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 for (i = 0; i < length; i++) {
10621 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010622 Py_RETURN_FALSE;
10623 }
10624 }
10625 Py_RETURN_TRUE;
10626}
10627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010628PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000010629 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630\n\
10631Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000010632iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633
10634static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010635unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010637 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638}
10639
Martin v. Löwis18e16552006-02-15 17:27:45 +000010640static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641unicode_length(PyUnicodeObject *self)
10642{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 if (PyUnicode_READY(self) == -1)
10644 return -1;
10645 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646}
10647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010648PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010651Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010652done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653
10654static PyObject *
10655unicode_ljust(PyUnicodeObject *self, PyObject *args)
10656{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010657 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 Py_UCS4 fillchar = ' ';
10659
10660 if (PyUnicode_READY(self) == -1)
10661 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010662
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010663 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664 return NULL;
10665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667 Py_INCREF(self);
10668 return (PyObject*) self;
10669 }
10670
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672}
10673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010674PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010675 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010677Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010678
10679static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010680unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010682 return fixup(self, fixlower);
10683}
10684
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010685#define LEFTSTRIP 0
10686#define RIGHTSTRIP 1
10687#define BOTHSTRIP 2
10688
10689/* Arrays indexed by above */
10690static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
10691
10692#define STRIPNAME(i) (stripformat[i]+3)
10693
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010694/* externally visible for str.strip(unicode) */
10695PyObject *
10696_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
10697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 void *data;
10699 int kind;
10700 Py_ssize_t i, j, len;
10701 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
10704 return NULL;
10705
10706 kind = PyUnicode_KIND(self);
10707 data = PyUnicode_DATA(self);
10708 len = PyUnicode_GET_LENGTH(self);
10709 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
10710 PyUnicode_DATA(sepobj),
10711 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010712
Benjamin Peterson14339b62009-01-31 16:36:08 +000010713 i = 0;
10714 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715 while (i < len &&
10716 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010717 i++;
10718 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010719 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010720
Benjamin Peterson14339b62009-01-31 16:36:08 +000010721 j = len;
10722 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 do {
10724 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010725 } while (j >= i &&
10726 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000010727 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010728 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010729
Victor Stinner12bab6d2011-10-01 01:53:49 +020010730 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010731}
10732
10733PyObject*
10734PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
10735{
10736 unsigned char *data;
10737 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020010738 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739
Victor Stinnerde636f32011-10-01 03:55:54 +020010740 if (PyUnicode_READY(self) == -1)
10741 return NULL;
10742
10743 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
10744
Victor Stinner12bab6d2011-10-01 01:53:49 +020010745 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010746 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010747 if (PyUnicode_CheckExact(self)) {
10748 Py_INCREF(self);
10749 return self;
10750 }
10751 else
10752 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010753 }
10754
Victor Stinner12bab6d2011-10-01 01:53:49 +020010755 length = end - start;
10756 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010757 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758
Victor Stinnerde636f32011-10-01 03:55:54 +020010759 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010760 PyErr_SetString(PyExc_IndexError, "string index out of range");
10761 return NULL;
10762 }
10763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 kind = PyUnicode_KIND(self);
10765 data = PyUnicode_1BYTE_DATA(self);
Victor Stinner034f6cf2011-09-30 02:26:44 +020010766 return PyUnicode_FromKindAndData(kind,
10767 data + PyUnicode_KIND_SIZE(kind, start),
Victor Stinner12bab6d2011-10-01 01:53:49 +020010768 length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769}
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770
10771static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010772do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 int kind;
10775 void *data;
10776 Py_ssize_t len, i, j;
10777
10778 if (PyUnicode_READY(self) == -1)
10779 return NULL;
10780
10781 kind = PyUnicode_KIND(self);
10782 data = PyUnicode_DATA(self);
10783 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010784
Benjamin Peterson14339b62009-01-31 16:36:08 +000010785 i = 0;
10786 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010788 i++;
10789 }
10790 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010791
Benjamin Peterson14339b62009-01-31 16:36:08 +000010792 j = len;
10793 if (striptype != LEFTSTRIP) {
10794 do {
10795 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010797 j++;
10798 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010799
Victor Stinner12bab6d2011-10-01 01:53:49 +020010800 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801}
10802
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010803
10804static PyObject *
10805do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
10806{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010807 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010808
Benjamin Peterson14339b62009-01-31 16:36:08 +000010809 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
10810 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010811
Benjamin Peterson14339b62009-01-31 16:36:08 +000010812 if (sep != NULL && sep != Py_None) {
10813 if (PyUnicode_Check(sep))
10814 return _PyUnicode_XStrip(self, striptype, sep);
10815 else {
10816 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010817 "%s arg must be None or str",
10818 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010819 return NULL;
10820 }
10821 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010822
Benjamin Peterson14339b62009-01-31 16:36:08 +000010823 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010824}
10825
10826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010827PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010828 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010829\n\
10830Return a copy of the string S with leading and trailing\n\
10831whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010832If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010833
10834static PyObject *
10835unicode_strip(PyUnicodeObject *self, PyObject *args)
10836{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010837 if (PyTuple_GET_SIZE(args) == 0)
10838 return do_strip(self, BOTHSTRIP); /* Common case */
10839 else
10840 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010841}
10842
10843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010844PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010845 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010846\n\
10847Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010848If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010849
10850static PyObject *
10851unicode_lstrip(PyUnicodeObject *self, PyObject *args)
10852{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010853 if (PyTuple_GET_SIZE(args) == 0)
10854 return do_strip(self, LEFTSTRIP); /* Common case */
10855 else
10856 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010857}
10858
10859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010860PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010861 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010862\n\
10863Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010864If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010865
10866static PyObject *
10867unicode_rstrip(PyUnicodeObject *self, PyObject *args)
10868{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010869 if (PyTuple_GET_SIZE(args) == 0)
10870 return do_strip(self, RIGHTSTRIP); /* Common case */
10871 else
10872 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010873}
10874
10875
Guido van Rossumd57fd912000-03-10 22:53:23 +000010876static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000010877unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878{
10879 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010880 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881
Georg Brandl222de0f2009-04-12 12:01:50 +000010882 if (len < 1) {
10883 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020010884 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000010885 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886
Tim Peters7a29bd52001-09-12 03:03:31 +000010887 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 /* no repeat, return original string */
10889 Py_INCREF(str);
10890 return (PyObject*) str;
10891 }
Tim Peters8f422462000-09-09 06:13:41 +000010892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 if (PyUnicode_READY(str) == -1)
10894 return NULL;
10895
Victor Stinnerc759f3e2011-10-01 03:09:58 +020010896 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020010897 PyErr_SetString(PyExc_OverflowError,
10898 "repeated string is too long");
10899 return NULL;
10900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020010902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010903 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904 if (!u)
10905 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020010906 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010908 if (PyUnicode_GET_LENGTH(str) == 1) {
10909 const int kind = PyUnicode_KIND(str);
10910 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
10911 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020010912 if (kind == PyUnicode_1BYTE_KIND)
10913 memset(to, (unsigned char)fill_char, len);
10914 else {
10915 for (n = 0; n < len; ++n)
10916 PyUnicode_WRITE(kind, to, n, fill_char);
10917 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 }
10919 else {
10920 /* number of characters copied this far */
10921 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
10922 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
10923 char *to = (char *) PyUnicode_DATA(u);
10924 Py_MEMCPY(to, PyUnicode_DATA(str),
10925 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000010926 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 n = (done <= nchars-done) ? done : nchars-done;
10928 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010929 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010931 }
10932
10933 return (PyObject*) u;
10934}
10935
Alexander Belopolsky40018472011-02-26 01:02:56 +000010936PyObject *
10937PyUnicode_Replace(PyObject *obj,
10938 PyObject *subobj,
10939 PyObject *replobj,
10940 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941{
10942 PyObject *self;
10943 PyObject *str1;
10944 PyObject *str2;
10945 PyObject *result;
10946
10947 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010948 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010949 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010951 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010952 Py_DECREF(self);
10953 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954 }
10955 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020010956 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 Py_DECREF(self);
10958 Py_DECREF(str1);
10959 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010961 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962 Py_DECREF(self);
10963 Py_DECREF(str1);
10964 Py_DECREF(str2);
10965 return result;
10966}
10967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010968PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000010969 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970\n\
10971Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000010972old replaced by new. If the optional argument count is\n\
10973given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
10975static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 PyObject *str1;
10979 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010980 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 PyObject *result;
10982
Martin v. Löwis18e16552006-02-15 17:27:45 +000010983 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010985 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000010986 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 str1 = PyUnicode_FromObject(str1);
10988 if (str1 == NULL || PyUnicode_READY(str1) == -1)
10989 return NULL;
10990 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020010991 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 Py_DECREF(str1);
10993 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000010994 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995
10996 result = replace(self, str1, str2, maxcount);
10997
10998 Py_DECREF(str1);
10999 Py_DECREF(str2);
11000 return result;
11001}
11002
Alexander Belopolsky40018472011-02-26 01:02:56 +000011003static PyObject *
11004unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011006 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 Py_ssize_t isize;
11008 Py_ssize_t osize, squote, dquote, i, o;
11009 Py_UCS4 max, quote;
11010 int ikind, okind;
11011 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011013 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011014 return NULL;
11015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 isize = PyUnicode_GET_LENGTH(unicode);
11017 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011019 /* Compute length of output, quote characters, and
11020 maximum character */
11021 osize = 2; /* quotes */
11022 max = 127;
11023 squote = dquote = 0;
11024 ikind = PyUnicode_KIND(unicode);
11025 for (i = 0; i < isize; i++) {
11026 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11027 switch (ch) {
11028 case '\'': squote++; osize++; break;
11029 case '"': dquote++; osize++; break;
11030 case '\\': case '\t': case '\r': case '\n':
11031 osize += 2; break;
11032 default:
11033 /* Fast-path ASCII */
11034 if (ch < ' ' || ch == 0x7f)
11035 osize += 4; /* \xHH */
11036 else if (ch < 0x7f)
11037 osize++;
11038 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11039 osize++;
11040 max = ch > max ? ch : max;
11041 }
11042 else if (ch < 0x100)
11043 osize += 4; /* \xHH */
11044 else if (ch < 0x10000)
11045 osize += 6; /* \uHHHH */
11046 else
11047 osize += 10; /* \uHHHHHHHH */
11048 }
11049 }
11050
11051 quote = '\'';
11052 if (squote) {
11053 if (dquote)
11054 /* Both squote and dquote present. Use squote,
11055 and escape them */
11056 osize += squote;
11057 else
11058 quote = '"';
11059 }
11060
11061 repr = PyUnicode_New(osize, max);
11062 if (repr == NULL)
11063 return NULL;
11064 okind = PyUnicode_KIND(repr);
11065 odata = PyUnicode_DATA(repr);
11066
11067 PyUnicode_WRITE(okind, odata, 0, quote);
11068 PyUnicode_WRITE(okind, odata, osize-1, quote);
11069
11070 for (i = 0, o = 1; i < isize; i++) {
11071 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011072
11073 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 if ((ch == quote) || (ch == '\\')) {
11075 PyUnicode_WRITE(okind, odata, o++, '\\');
11076 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011077 continue;
11078 }
11079
Benjamin Peterson29060642009-01-31 22:14:21 +000011080 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011081 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 PyUnicode_WRITE(okind, odata, o++, '\\');
11083 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011084 }
11085 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086 PyUnicode_WRITE(okind, odata, o++, '\\');
11087 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011088 }
11089 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090 PyUnicode_WRITE(okind, odata, o++, '\\');
11091 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011092 }
11093
11094 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011095 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011096 PyUnicode_WRITE(okind, odata, o++, '\\');
11097 PyUnicode_WRITE(okind, odata, o++, 'x');
11098 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11099 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011100 }
11101
Georg Brandl559e5d72008-06-11 18:37:52 +000011102 /* Copy ASCII characters as-is */
11103 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011105 }
11106
Benjamin Peterson29060642009-01-31 22:14:21 +000011107 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011108 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011109 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011110 (categories Z* and C* except ASCII space)
11111 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011113 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 if (ch <= 0xff) {
11115 PyUnicode_WRITE(okind, odata, o++, '\\');
11116 PyUnicode_WRITE(okind, odata, o++, 'x');
11117 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11118 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011119 }
11120 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011121 else if (ch >= 0x10000) {
11122 PyUnicode_WRITE(okind, odata, o++, '\\');
11123 PyUnicode_WRITE(okind, odata, o++, 'U');
11124 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11125 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11126 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11127 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11128 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11129 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11130 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11131 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011132 }
11133 /* Map 16-bit characters to '\uxxxx' */
11134 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 PyUnicode_WRITE(okind, odata, o++, '\\');
11136 PyUnicode_WRITE(okind, odata, o++, 'u');
11137 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11138 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11139 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11140 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011141 }
11142 }
11143 /* Copy characters as-is */
11144 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011146 }
11147 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 /* Closing quote already added at the beginning */
Walter Dörwald79e913e2007-05-12 11:08:06 +000011150 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151}
11152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011153PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011154 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155\n\
11156Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011157such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158arguments start and end are interpreted as in slice notation.\n\
11159\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011160Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161
11162static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011163unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164{
Jesus Ceaac451502011-04-20 17:09:23 +020011165 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011166 Py_ssize_t start;
11167 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011168 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169
Jesus Ceaac451502011-04-20 17:09:23 +020011170 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11171 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 if (PyUnicode_READY(self) == -1)
11175 return NULL;
11176 if (PyUnicode_READY(substring) == -1)
11177 return NULL;
11178
11179 result = any_find_slice(
11180 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11181 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011182 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
11184 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011185
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 if (result == -2)
11187 return NULL;
11188
Christian Heimes217cfd12007-12-02 14:31:20 +000011189 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190}
11191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011192PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011193 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011195Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196
11197static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199{
Jesus Ceaac451502011-04-20 17:09:23 +020011200 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011201 Py_ssize_t start;
11202 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011203 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
Jesus Ceaac451502011-04-20 17:09:23 +020011205 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11206 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011207 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 if (PyUnicode_READY(self) == -1)
11210 return NULL;
11211 if (PyUnicode_READY(substring) == -1)
11212 return NULL;
11213
11214 result = any_find_slice(
11215 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11216 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011217 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
11219 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011220
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 if (result == -2)
11222 return NULL;
11223
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 if (result < 0) {
11225 PyErr_SetString(PyExc_ValueError, "substring not found");
11226 return NULL;
11227 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228
Christian Heimes217cfd12007-12-02 14:31:20 +000011229 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230}
11231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011232PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011235Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011236done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237
11238static PyObject *
11239unicode_rjust(PyUnicodeObject *self, PyObject *args)
11240{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011241 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 Py_UCS4 fillchar = ' ';
11243
Victor Stinnere9a29352011-10-01 02:14:59 +020011244 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011245 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011246
Victor Stinnere9a29352011-10-01 02:14:59 +020011247 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248 return NULL;
11249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011250 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 Py_INCREF(self);
11252 return (PyObject*) self;
11253 }
11254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011255 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256}
11257
Alexander Belopolsky40018472011-02-26 01:02:56 +000011258PyObject *
11259PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260{
11261 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011262
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263 s = PyUnicode_FromObject(s);
11264 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011265 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 if (sep != NULL) {
11267 sep = PyUnicode_FromObject(sep);
11268 if (sep == NULL) {
11269 Py_DECREF(s);
11270 return NULL;
11271 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 }
11273
11274 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11275
11276 Py_DECREF(s);
11277 Py_XDECREF(sep);
11278 return result;
11279}
11280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011281PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283\n\
11284Return a list of the words in S, using sep as the\n\
11285delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011286splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011287whitespace string is a separator and empty strings are\n\
11288removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289
11290static PyObject*
11291unicode_split(PyUnicodeObject *self, PyObject *args)
11292{
11293 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011294 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Martin v. Löwis18e16552006-02-15 17:27:45 +000011296 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 return NULL;
11298
11299 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011302 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305}
11306
Thomas Wouters477c8d52006-05-27 19:21:47 +000011307PyObject *
11308PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11309{
11310 PyObject* str_obj;
11311 PyObject* sep_obj;
11312 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 int kind1, kind2, kind;
11314 void *buf1 = NULL, *buf2 = NULL;
11315 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011316
11317 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011318 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011320 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011322 Py_DECREF(str_obj);
11323 return NULL;
11324 }
11325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 kind1 = PyUnicode_KIND(str_in);
11327 kind2 = PyUnicode_KIND(sep_obj);
11328 kind = kind1 > kind2 ? kind1 : kind2;
11329 buf1 = PyUnicode_DATA(str_in);
11330 if (kind1 != kind)
11331 buf1 = _PyUnicode_AsKind(str_in, kind);
11332 if (!buf1)
11333 goto onError;
11334 buf2 = PyUnicode_DATA(sep_obj);
11335 if (kind2 != kind)
11336 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11337 if (!buf2)
11338 goto onError;
11339 len1 = PyUnicode_GET_LENGTH(str_obj);
11340 len2 = PyUnicode_GET_LENGTH(sep_obj);
11341
11342 switch(PyUnicode_KIND(str_in)) {
11343 case PyUnicode_1BYTE_KIND:
11344 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11345 break;
11346 case PyUnicode_2BYTE_KIND:
11347 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11348 break;
11349 case PyUnicode_4BYTE_KIND:
11350 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11351 break;
11352 default:
11353 assert(0);
11354 out = 0;
11355 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011356
11357 Py_DECREF(sep_obj);
11358 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 if (kind1 != kind)
11360 PyMem_Free(buf1);
11361 if (kind2 != kind)
11362 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011363
11364 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 onError:
11366 Py_DECREF(sep_obj);
11367 Py_DECREF(str_obj);
11368 if (kind1 != kind && buf1)
11369 PyMem_Free(buf1);
11370 if (kind2 != kind && buf2)
11371 PyMem_Free(buf2);
11372 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011373}
11374
11375
11376PyObject *
11377PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11378{
11379 PyObject* str_obj;
11380 PyObject* sep_obj;
11381 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 int kind1, kind2, kind;
11383 void *buf1 = NULL, *buf2 = NULL;
11384 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011385
11386 str_obj = PyUnicode_FromObject(str_in);
11387 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011388 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011389 sep_obj = PyUnicode_FromObject(sep_in);
11390 if (!sep_obj) {
11391 Py_DECREF(str_obj);
11392 return NULL;
11393 }
11394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 kind1 = PyUnicode_KIND(str_in);
11396 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011397 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 buf1 = PyUnicode_DATA(str_in);
11399 if (kind1 != kind)
11400 buf1 = _PyUnicode_AsKind(str_in, kind);
11401 if (!buf1)
11402 goto onError;
11403 buf2 = PyUnicode_DATA(sep_obj);
11404 if (kind2 != kind)
11405 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11406 if (!buf2)
11407 goto onError;
11408 len1 = PyUnicode_GET_LENGTH(str_obj);
11409 len2 = PyUnicode_GET_LENGTH(sep_obj);
11410
11411 switch(PyUnicode_KIND(str_in)) {
11412 case PyUnicode_1BYTE_KIND:
11413 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11414 break;
11415 case PyUnicode_2BYTE_KIND:
11416 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11417 break;
11418 case PyUnicode_4BYTE_KIND:
11419 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11420 break;
11421 default:
11422 assert(0);
11423 out = 0;
11424 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011425
11426 Py_DECREF(sep_obj);
11427 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 if (kind1 != kind)
11429 PyMem_Free(buf1);
11430 if (kind2 != kind)
11431 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011432
11433 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 onError:
11435 Py_DECREF(sep_obj);
11436 Py_DECREF(str_obj);
11437 if (kind1 != kind && buf1)
11438 PyMem_Free(buf1);
11439 if (kind2 != kind && buf2)
11440 PyMem_Free(buf2);
11441 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011442}
11443
11444PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011446\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011447Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011448the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011449found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011450
11451static PyObject*
11452unicode_partition(PyUnicodeObject *self, PyObject *separator)
11453{
11454 return PyUnicode_Partition((PyObject *)self, separator);
11455}
11456
11457PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011458 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011459\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011460Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011461the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011462separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011463
11464static PyObject*
11465unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
11466{
11467 return PyUnicode_RPartition((PyObject *)self, separator);
11468}
11469
Alexander Belopolsky40018472011-02-26 01:02:56 +000011470PyObject *
11471PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011472{
11473 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011474
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011475 s = PyUnicode_FromObject(s);
11476 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011477 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (sep != NULL) {
11479 sep = PyUnicode_FromObject(sep);
11480 if (sep == NULL) {
11481 Py_DECREF(s);
11482 return NULL;
11483 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011484 }
11485
11486 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11487
11488 Py_DECREF(s);
11489 Py_XDECREF(sep);
11490 return result;
11491}
11492
11493PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011494 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011495\n\
11496Return a list of the words in S, using sep as the\n\
11497delimiter string, starting at the end of the string and\n\
11498working to the front. If maxsplit is given, at most maxsplit\n\
11499splits are done. If sep is not specified, any whitespace string\n\
11500is a separator.");
11501
11502static PyObject*
11503unicode_rsplit(PyUnicodeObject *self, PyObject *args)
11504{
11505 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011506 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011507
Martin v. Löwis18e16552006-02-15 17:27:45 +000011508 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011509 return NULL;
11510
11511 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011513 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011515 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011517}
11518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011520 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521\n\
11522Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000011523Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011524is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
11526static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011527unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011529 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000011530 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011532 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
11533 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534 return NULL;
11535
Guido van Rossum86662912000-04-11 15:38:46 +000011536 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
11539static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000011540PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Walter Dörwald346737f2007-05-31 10:44:43 +000011542 if (PyUnicode_CheckExact(self)) {
11543 Py_INCREF(self);
11544 return self;
11545 } else
11546 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020011547 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548}
11549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011550PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011552\n\
11553Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011554and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555
11556static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011557unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 return fixup(self, fixswapcase);
11560}
11561
Georg Brandlceee0772007-11-27 23:48:05 +000011562PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011563 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011564\n\
11565Return a translation table usable for str.translate().\n\
11566If there is only one argument, it must be a dictionary mapping Unicode\n\
11567ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011568Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011569If there are two arguments, they must be strings of equal length, and\n\
11570in the resulting dictionary, each character in x will be mapped to the\n\
11571character at the same position in y. If there is a third argument, it\n\
11572must be a string, whose characters will be mapped to None in the result.");
11573
11574static PyObject*
11575unicode_maketrans(PyUnicodeObject *null, PyObject *args)
11576{
11577 PyObject *x, *y = NULL, *z = NULL;
11578 PyObject *new = NULL, *key, *value;
11579 Py_ssize_t i = 0;
11580 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011581
Georg Brandlceee0772007-11-27 23:48:05 +000011582 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
11583 return NULL;
11584 new = PyDict_New();
11585 if (!new)
11586 return NULL;
11587 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011588 int x_kind, y_kind, z_kind;
11589 void *x_data, *y_data, *z_data;
11590
Georg Brandlceee0772007-11-27 23:48:05 +000011591 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000011592 if (!PyUnicode_Check(x)) {
11593 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
11594 "be a string if there is a second argument");
11595 goto err;
11596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011598 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
11599 "arguments must have equal length");
11600 goto err;
11601 }
11602 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 x_kind = PyUnicode_KIND(x);
11604 y_kind = PyUnicode_KIND(y);
11605 x_data = PyUnicode_DATA(x);
11606 y_data = PyUnicode_DATA(y);
11607 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
11608 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
11609 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011610 if (!key || !value)
11611 goto err;
11612 res = PyDict_SetItem(new, key, value);
11613 Py_DECREF(key);
11614 Py_DECREF(value);
11615 if (res < 0)
11616 goto err;
11617 }
11618 /* create entries for deleting chars in z */
11619 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 z_kind = PyUnicode_KIND(z);
11621 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000011622 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011624 if (!key)
11625 goto err;
11626 res = PyDict_SetItem(new, key, Py_None);
11627 Py_DECREF(key);
11628 if (res < 0)
11629 goto err;
11630 }
11631 }
11632 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 int kind;
11634 void *data;
11635
Georg Brandlceee0772007-11-27 23:48:05 +000011636 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000011637 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011638 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
11639 "to maketrans it must be a dict");
11640 goto err;
11641 }
11642 /* copy entries into the new dict, converting string keys to int keys */
11643 while (PyDict_Next(x, &i, &key, &value)) {
11644 if (PyUnicode_Check(key)) {
11645 /* convert string keys to integer keys */
11646 PyObject *newkey;
11647 if (PyUnicode_GET_SIZE(key) != 1) {
11648 PyErr_SetString(PyExc_ValueError, "string keys in translate "
11649 "table must be of length 1");
11650 goto err;
11651 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 kind = PyUnicode_KIND(key);
11653 data = PyUnicode_DATA(key);
11654 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000011655 if (!newkey)
11656 goto err;
11657 res = PyDict_SetItem(new, newkey, value);
11658 Py_DECREF(newkey);
11659 if (res < 0)
11660 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000011661 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011662 /* just keep integer keys */
11663 if (PyDict_SetItem(new, key, value) < 0)
11664 goto err;
11665 } else {
11666 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
11667 "be strings or integers");
11668 goto err;
11669 }
11670 }
11671 }
11672 return new;
11673 err:
11674 Py_DECREF(new);
11675 return NULL;
11676}
11677
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011678PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011679 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680\n\
11681Return a copy of the string S, where all characters have been mapped\n\
11682through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011683Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000011684Unmapped characters are left untouched. Characters mapped to None\n\
11685are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686
11687static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691}
11692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011693PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011696Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
11698static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011699unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701 return fixup(self, fixupper);
11702}
11703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011704PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011705 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000011707Pad a numeric string S with zeros on the left, to fill a field\n\
11708of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709
11710static PyObject *
11711unicode_zfill(PyUnicodeObject *self, PyObject *args)
11712{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011713 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714 PyUnicodeObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011715 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716 int kind;
11717 void *data;
11718 Py_UCS4 chr;
11719
11720 if (PyUnicode_READY(self) == -1)
11721 return NULL;
11722
Martin v. Löwis18e16552006-02-15 17:27:45 +000011723 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724 return NULL;
11725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000011727 if (PyUnicode_CheckExact(self)) {
11728 Py_INCREF(self);
11729 return (PyObject*) self;
11730 }
11731 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020011732 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 }
11734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
11737 u = pad(self, fill, 0, '0');
11738
Walter Dörwald068325e2002-04-15 13:36:47 +000011739 if (u == NULL)
11740 return NULL;
11741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 kind = PyUnicode_KIND(u);
11743 data = PyUnicode_DATA(u);
11744 chr = PyUnicode_READ(kind, data, fill);
11745
11746 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 PyUnicode_WRITE(kind, data, 0, chr);
11749 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750 }
11751
11752 return (PyObject*) u;
11753}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754
11755#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011756static PyObject *
11757unicode__decimal2ascii(PyObject *self)
11758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011760}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761#endif
11762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011763PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011766Return True if S starts with the specified prefix, False otherwise.\n\
11767With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011768With optional end, stop comparing S at that position.\n\
11769prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
11771static PyObject *
11772unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011775 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011777 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011778 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011779 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
Jesus Ceaac451502011-04-20 17:09:23 +020011781 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011783 if (PyTuple_Check(subobj)) {
11784 Py_ssize_t i;
11785 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11786 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011787 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011788 if (substring == NULL)
11789 return NULL;
11790 result = tailmatch(self, substring, start, end, -1);
11791 Py_DECREF(substring);
11792 if (result) {
11793 Py_RETURN_TRUE;
11794 }
11795 }
11796 /* nothing matched */
11797 Py_RETURN_FALSE;
11798 }
11799 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011800 if (substring == NULL) {
11801 if (PyErr_ExceptionMatches(PyExc_TypeError))
11802 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
11803 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011805 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011806 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011808 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809}
11810
11811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011812PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011815Return True if S ends with the specified suffix, False otherwise.\n\
11816With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011817With optional end, stop comparing S at that position.\n\
11818suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
11820static PyObject *
11821unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011822 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011824 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011826 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011827 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011828 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829
Jesus Ceaac451502011-04-20 17:09:23 +020011830 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011832 if (PyTuple_Check(subobj)) {
11833 Py_ssize_t i;
11834 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11835 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011836 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011837 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011838 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011839 result = tailmatch(self, substring, start, end, +1);
11840 Py_DECREF(substring);
11841 if (result) {
11842 Py_RETURN_TRUE;
11843 }
11844 }
11845 Py_RETURN_FALSE;
11846 }
11847 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011848 if (substring == NULL) {
11849 if (PyErr_ExceptionMatches(PyExc_TypeError))
11850 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
11851 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011852 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011853 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011854 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011856 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857}
11858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000011860
11861PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011862 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011863\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011864Return a formatted version of S, using substitutions from args and kwargs.\n\
11865The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000011866
Eric Smith27bbca62010-11-04 17:06:58 +000011867PyDoc_STRVAR(format_map__doc__,
11868 "S.format_map(mapping) -> str\n\
11869\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011870Return a formatted version of S, using substitutions from mapping.\n\
11871The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000011872
Eric Smith4a7d76d2008-05-30 18:10:19 +000011873static PyObject *
11874unicode__format__(PyObject* self, PyObject* args)
11875{
11876 PyObject *format_spec;
11877
11878 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
11879 return NULL;
11880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011881 return _PyUnicode_FormatAdvanced(self, format_spec, 0,
11882 PyUnicode_GET_LENGTH(format_spec));
Eric Smith4a7d76d2008-05-30 18:10:19 +000011883}
11884
Eric Smith8c663262007-08-25 02:26:07 +000011885PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011886 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000011887\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000011888Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000011889
11890static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011891unicode__sizeof__(PyUnicodeObject *v)
11892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 Py_ssize_t size;
11894
11895 /* If it's a compact object, account for base structure +
11896 character data. */
11897 if (PyUnicode_IS_COMPACT_ASCII(v))
11898 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
11899 else if (PyUnicode_IS_COMPACT(v))
11900 size = sizeof(PyCompactUnicodeObject) +
11901 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
11902 else {
11903 /* If it is a two-block object, account for base object, and
11904 for character block if present. */
11905 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020011906 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 size += (PyUnicode_GET_LENGTH(v) + 1) *
11908 PyUnicode_CHARACTER_SIZE(v);
11909 }
11910 /* If the wstr pointer is present, account for it unless it is shared
11911 with the data pointer. Since PyUnicode_DATA will crash if the object
11912 is not ready, check whether it's either not ready (in which case the
11913 data is entirely in wstr) or if the data is not shared. */
11914 if (_PyUnicode_WSTR(v) &&
11915 (!PyUnicode_IS_READY(v) ||
11916 (PyUnicode_DATA(v) != _PyUnicode_WSTR(v))))
11917 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020011918 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020011919 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920
11921 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011922}
11923
11924PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011925 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011926
11927static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020011928unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011929{
Victor Stinner034f6cf2011-09-30 02:26:44 +020011930 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 if (!copy)
11932 return NULL;
11933 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000011934}
11935
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936static PyMethodDef unicode_methods[] = {
11937
11938 /* Order is according to common usage: often used methods should
11939 appear first, since lookup is done sequentially. */
11940
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000011941 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011942 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
11943 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011944 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011945 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
11946 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
11947 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
11948 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
11949 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
11950 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
11951 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011952 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011953 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
11954 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
11955 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011956 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011957 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
11958 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
11959 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011960 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000011961 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011962 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011963 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011964 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
11965 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
11966 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
11967 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
11968 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
11969 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
11970 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
11971 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
11972 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
11973 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
11974 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
11975 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
11976 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
11977 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000011978 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000011979 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011980 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000011981 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000011982 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000011983 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000011984 {"maketrans", (PyCFunction) unicode_maketrans,
11985 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000011986 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000011987#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011988 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011989#endif
11990
11991#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011992 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011993 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994#endif
11995
Benjamin Peterson14339b62009-01-31 16:36:08 +000011996 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997 {NULL, NULL}
11998};
11999
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012000static PyObject *
12001unicode_mod(PyObject *v, PyObject *w)
12002{
Brian Curtindfc80e32011-08-10 20:28:54 -050012003 if (!PyUnicode_Check(v))
12004 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012006}
12007
12008static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012009 0, /*nb_add*/
12010 0, /*nb_subtract*/
12011 0, /*nb_multiply*/
12012 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012013};
12014
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012016 (lenfunc) unicode_length, /* sq_length */
12017 PyUnicode_Concat, /* sq_concat */
12018 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12019 (ssizeargfunc) unicode_getitem, /* sq_item */
12020 0, /* sq_slice */
12021 0, /* sq_ass_item */
12022 0, /* sq_ass_slice */
12023 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024};
12025
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012026static PyObject*
12027unicode_subscript(PyUnicodeObject* self, PyObject* item)
12028{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 if (PyUnicode_READY(self) == -1)
12030 return NULL;
12031
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012032 if (PyIndex_Check(item)) {
12033 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012034 if (i == -1 && PyErr_Occurred())
12035 return NULL;
12036 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012038 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012039 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012040 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 const Py_UNICODE* source_buf;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012042 Py_UNICODE* result_buf;
12043 PyObject* result;
12044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012047 return NULL;
12048 }
12049
12050 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 return PyUnicode_New(0, 0);
12052 } else if (start == 0 && step == 1 &&
12053 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012054 PyUnicode_CheckExact(self)) {
12055 Py_INCREF(self);
12056 return (PyObject *)self;
12057 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012058 return PyUnicode_Substring((PyObject*)self,
12059 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012060 } else {
12061 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +000012062 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
12063 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012064
Benjamin Peterson29060642009-01-31 22:14:21 +000012065 if (result_buf == NULL)
12066 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012067
12068 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12069 result_buf[i] = source_buf[cur];
12070 }
Tim Petersced69f82003-09-16 20:30:58 +000012071
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012072 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +000012073 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012074 return result;
12075 }
12076 } else {
12077 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12078 return NULL;
12079 }
12080}
12081
12082static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012083 (lenfunc)unicode_length, /* mp_length */
12084 (binaryfunc)unicode_subscript, /* mp_subscript */
12085 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012086};
12087
Guido van Rossumd57fd912000-03-10 22:53:23 +000012088
Guido van Rossumd57fd912000-03-10 22:53:23 +000012089/* Helpers for PyUnicode_Format() */
12090
12091static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012092getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012094 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 (*p_argidx)++;
12097 if (arglen < 0)
12098 return args;
12099 else
12100 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101 }
12102 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012103 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104 return NULL;
12105}
12106
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012107/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012109static PyObject *
12110formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012112 char *p;
12113 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012115
Guido van Rossumd57fd912000-03-10 22:53:23 +000012116 x = PyFloat_AsDouble(v);
12117 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012118 return NULL;
12119
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012122
Eric Smith0923d1d2009-04-16 20:16:10 +000012123 p = PyOS_double_to_string(x, type, prec,
12124 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012125 if (p == NULL)
12126 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012128 PyMem_Free(p);
12129 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130}
12131
Tim Peters38fd5b62000-09-21 05:43:11 +000012132static PyObject*
12133formatlong(PyObject *val, int flags, int prec, int type)
12134{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 char *buf;
12136 int len;
12137 PyObject *str; /* temporary string object. */
12138 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012139
Benjamin Peterson14339b62009-01-31 16:36:08 +000012140 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12141 if (!str)
12142 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012144 Py_DECREF(str);
12145 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012146}
12147
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149formatchar(Py_UCS4 *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012150 size_t buflen,
12151 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012153 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012154 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 if (PyUnicode_GET_LENGTH(v) == 1) {
12156 buf[0] = PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 buf[1] = '\0';
12158 return 1;
12159 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 goto onError;
12161 }
12162 else {
12163 /* Integer input truncated to a character */
12164 long x;
12165 x = PyLong_AsLong(v);
12166 if (x == -1 && PyErr_Occurred())
12167 goto onError;
12168
12169 if (x < 0 || x > 0x10ffff) {
12170 PyErr_SetString(PyExc_OverflowError,
12171 "%c arg not in range(0x110000)");
12172 return -1;
12173 }
12174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 buf[0] = (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012176 buf[1] = '\0';
12177 return 1;
12178 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012179
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012181 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012182 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012183 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184}
12185
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012186/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012187 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012188*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012189#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012190
Alexander Belopolsky40018472011-02-26 01:02:56 +000012191PyObject *
12192PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 void *fmt;
12195 int fmtkind;
12196 PyObject *result;
12197 Py_UCS4 *res, *res0;
12198 Py_UCS4 max;
12199 int kind;
12200 Py_ssize_t fmtcnt, fmtpos, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202 PyObject *dict = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 PyUnicodeObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +000012204
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012206 PyErr_BadInternalCall();
12207 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12210 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012211 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 fmt = PyUnicode_DATA(uformat);
12213 fmtkind = PyUnicode_KIND(uformat);
12214 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12215 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216
12217 reslen = rescnt = fmtcnt + 100;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 res = res0 = PyMem_Malloc(reslen * sizeof(Py_UCS4));
12219 if (res0 == NULL) {
12220 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012221 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223
12224 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012225 arglen = PyTuple_Size(args);
12226 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 }
12228 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 arglen = -1;
12230 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012232 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012233 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235
12236 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012238 if (--rescnt < 0) {
12239 rescnt = fmtcnt + 100;
12240 reslen += rescnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012241 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12242 if (res0 == NULL){
12243 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245 }
12246 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012247 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 *res++ = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012250 }
12251 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 /* Got a format specifier */
12253 int flags = 0;
12254 Py_ssize_t width = -1;
12255 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 Py_UCS4 c = '\0';
12257 Py_UCS4 fill;
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 int isnumok;
12259 PyObject *v = NULL;
12260 PyObject *temp = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012261 void *pbuf;
12262 Py_ssize_t pindex;
Benjamin Peterson29060642009-01-31 22:14:21 +000012263 Py_UNICODE sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 Py_ssize_t len, len1;
12265 Py_UCS4 formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 fmtpos++;
12268 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12269 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 Py_ssize_t keylen;
12271 PyObject *key;
12272 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012273
Benjamin Peterson29060642009-01-31 22:14:21 +000012274 if (dict == NULL) {
12275 PyErr_SetString(PyExc_TypeError,
12276 "format requires a mapping");
12277 goto onError;
12278 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012279 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012280 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 /* Skip over balanced parentheses */
12283 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012284 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012285 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012287 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012290 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012291 if (fmtcnt < 0 || pcount > 0) {
12292 PyErr_SetString(PyExc_ValueError,
12293 "incomplete format key");
12294 goto onError;
12295 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012296 key = PyUnicode_Substring((PyObject*)uformat,
12297 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012298 if (key == NULL)
12299 goto onError;
12300 if (args_owned) {
12301 Py_DECREF(args);
12302 args_owned = 0;
12303 }
12304 args = PyObject_GetItem(dict, key);
12305 Py_DECREF(key);
12306 if (args == NULL) {
12307 goto onError;
12308 }
12309 args_owned = 1;
12310 arglen = -1;
12311 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012312 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012313 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012315 case '-': flags |= F_LJUST; continue;
12316 case '+': flags |= F_SIGN; continue;
12317 case ' ': flags |= F_BLANK; continue;
12318 case '#': flags |= F_ALT; continue;
12319 case '0': flags |= F_ZERO; continue;
12320 }
12321 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 if (c == '*') {
12324 v = getnextarg(args, arglen, &argidx);
12325 if (v == NULL)
12326 goto onError;
12327 if (!PyLong_Check(v)) {
12328 PyErr_SetString(PyExc_TypeError,
12329 "* wants int");
12330 goto onError;
12331 }
12332 width = PyLong_AsLong(v);
12333 if (width == -1 && PyErr_Occurred())
12334 goto onError;
12335 if (width < 0) {
12336 flags |= F_LJUST;
12337 width = -width;
12338 }
12339 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012341 }
12342 else if (c >= '0' && c <= '9') {
12343 width = c - '0';
12344 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012346 if (c < '0' || c > '9')
12347 break;
12348 if ((width*10) / 10 != width) {
12349 PyErr_SetString(PyExc_ValueError,
12350 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012351 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012352 }
12353 width = width*10 + (c - '0');
12354 }
12355 }
12356 if (c == '.') {
12357 prec = 0;
12358 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012360 if (c == '*') {
12361 v = getnextarg(args, arglen, &argidx);
12362 if (v == NULL)
12363 goto onError;
12364 if (!PyLong_Check(v)) {
12365 PyErr_SetString(PyExc_TypeError,
12366 "* wants int");
12367 goto onError;
12368 }
12369 prec = PyLong_AsLong(v);
12370 if (prec == -1 && PyErr_Occurred())
12371 goto onError;
12372 if (prec < 0)
12373 prec = 0;
12374 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 }
12377 else if (c >= '0' && c <= '9') {
12378 prec = c - '0';
12379 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 if (c < '0' || c > '9')
12382 break;
12383 if ((prec*10) / 10 != prec) {
12384 PyErr_SetString(PyExc_ValueError,
12385 "prec too big");
12386 goto onError;
12387 }
12388 prec = prec*10 + (c - '0');
12389 }
12390 }
12391 } /* prec */
12392 if (fmtcnt >= 0) {
12393 if (c == 'h' || c == 'l' || c == 'L') {
12394 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 }
12397 }
12398 if (fmtcnt < 0) {
12399 PyErr_SetString(PyExc_ValueError,
12400 "incomplete format");
12401 goto onError;
12402 }
12403 if (c != '%') {
12404 v = getnextarg(args, arglen, &argidx);
12405 if (v == NULL)
12406 goto onError;
12407 }
12408 sign = 0;
12409 fill = ' ';
12410 switch (c) {
12411
12412 case '%':
12413 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012415 /* presume that buffer length is at least 1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 PyUnicode_WRITE(kind, pbuf, 0, '%');
Benjamin Peterson29060642009-01-31 22:14:21 +000012417 len = 1;
12418 break;
12419
12420 case 's':
12421 case 'r':
12422 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012423 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012424 temp = v;
12425 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012426 }
12427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012428 if (c == 's')
12429 temp = PyObject_Str(v);
12430 else if (c == 'r')
12431 temp = PyObject_Repr(v);
12432 else
12433 temp = PyObject_ASCII(v);
12434 if (temp == NULL)
12435 goto onError;
12436 if (PyUnicode_Check(temp))
12437 /* nothing to do */;
12438 else {
12439 Py_DECREF(temp);
12440 PyErr_SetString(PyExc_TypeError,
12441 "%s argument has non-string str()");
12442 goto onError;
12443 }
12444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012445 if (PyUnicode_READY(temp) == -1) {
12446 Py_CLEAR(temp);
12447 goto onError;
12448 }
12449 pbuf = PyUnicode_DATA(temp);
12450 kind = PyUnicode_KIND(temp);
12451 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 if (prec >= 0 && len > prec)
12453 len = prec;
12454 break;
12455
12456 case 'i':
12457 case 'd':
12458 case 'u':
12459 case 'o':
12460 case 'x':
12461 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000012462 isnumok = 0;
12463 if (PyNumber_Check(v)) {
12464 PyObject *iobj=NULL;
12465
12466 if (PyLong_Check(v)) {
12467 iobj = v;
12468 Py_INCREF(iobj);
12469 }
12470 else {
12471 iobj = PyNumber_Long(v);
12472 }
12473 if (iobj!=NULL) {
12474 if (PyLong_Check(iobj)) {
12475 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070012476 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 Py_DECREF(iobj);
12478 if (!temp)
12479 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012480 if (PyUnicode_READY(temp) == -1) {
12481 Py_CLEAR(temp);
12482 goto onError;
12483 }
12484 pbuf = PyUnicode_DATA(temp);
12485 kind = PyUnicode_KIND(temp);
12486 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012487 sign = 1;
12488 }
12489 else {
12490 Py_DECREF(iobj);
12491 }
12492 }
12493 }
12494 if (!isnumok) {
12495 PyErr_Format(PyExc_TypeError,
12496 "%%%c format: a number is required, "
12497 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
12498 goto onError;
12499 }
12500 if (flags & F_ZERO)
12501 fill = '0';
12502 break;
12503
12504 case 'e':
12505 case 'E':
12506 case 'f':
12507 case 'F':
12508 case 'g':
12509 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012510 temp = formatfloat(v, flags, prec, c);
12511 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000012512 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 if (PyUnicode_READY(temp) == -1) {
12514 Py_CLEAR(temp);
12515 goto onError;
12516 }
12517 pbuf = PyUnicode_DATA(temp);
12518 kind = PyUnicode_KIND(temp);
12519 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 sign = 1;
12521 if (flags & F_ZERO)
12522 fill = '0';
12523 break;
12524
12525 case 'c':
12526 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012527 kind = PyUnicode_4BYTE_KIND;
Victor Stinnerb9dcffb2011-09-29 00:39:24 +020012528 len = formatchar(pbuf, Py_ARRAY_LENGTH(formatbuf), v);
Benjamin Peterson29060642009-01-31 22:14:21 +000012529 if (len < 0)
12530 goto onError;
12531 break;
12532
12533 default:
12534 PyErr_Format(PyExc_ValueError,
12535 "unsupported format character '%c' (0x%x) "
12536 "at index %zd",
12537 (31<=c && c<=126) ? (char)c : '?',
12538 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000012540 goto onError;
12541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 /* pbuf is initialized here. */
12543 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000012544 if (sign) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012545 if (PyUnicode_READ(kind, pbuf, pindex) == '-' ||
12546 PyUnicode_READ(kind, pbuf, pindex) == '+') {
12547 sign = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012548 len--;
12549 }
12550 else if (flags & F_SIGN)
12551 sign = '+';
12552 else if (flags & F_BLANK)
12553 sign = ' ';
12554 else
12555 sign = 0;
12556 }
12557 if (width < len)
12558 width = len;
12559 if (rescnt - (sign != 0) < width) {
12560 reslen -= rescnt;
12561 rescnt = width + fmtcnt + 100;
12562 reslen += rescnt;
12563 if (reslen < 0) {
12564 Py_XDECREF(temp);
12565 PyErr_NoMemory();
12566 goto onError;
12567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12569 if (res0 == 0) {
12570 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012571 Py_XDECREF(temp);
12572 goto onError;
12573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012575 }
12576 if (sign) {
12577 if (fill != ' ')
12578 *res++ = sign;
12579 rescnt--;
12580 if (width > len)
12581 width--;
12582 }
12583 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12585 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 if (fill != ' ') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12588 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012589 }
12590 rescnt -= 2;
12591 width -= 2;
12592 if (width < 0)
12593 width = 0;
12594 len -= 2;
12595 }
12596 if (width > len && !(flags & F_LJUST)) {
12597 do {
12598 --rescnt;
12599 *res++ = fill;
12600 } while (--width > len);
12601 }
12602 if (fill == ' ') {
12603 if (sign)
12604 *res++ = sign;
12605 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012606 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12607 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
12608 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12609 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012610 }
12611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612 /* Copy all characters, preserving len */
12613 len1 = len;
12614 while (len1--) {
12615 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12616 rescnt--;
12617 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012618 while (--width >= len) {
12619 --rescnt;
12620 *res++ = ' ';
12621 }
12622 if (dict && (argidx < arglen) && c != '%') {
12623 PyErr_SetString(PyExc_TypeError,
12624 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +000012625 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012626 goto onError;
12627 }
12628 Py_XDECREF(temp);
12629 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630 } /* until end */
12631 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 PyErr_SetString(PyExc_TypeError,
12633 "not all arguments converted during string formatting");
12634 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635 }
12636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637
12638 for (max=0, res = res0; res < res0+reslen-rescnt; res++)
12639 if (*res > max)
12640 max = *res;
12641 result = PyUnicode_New(reslen - rescnt, max);
12642 if (!result)
Benjamin Peterson29060642009-01-31 22:14:21 +000012643 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012644 kind = PyUnicode_KIND(result);
12645 for (res = res0; res < res0+reslen-rescnt; res++)
12646 PyUnicode_WRITE(kind, PyUnicode_DATA(result), res-res0, *res);
12647 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012649 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650 }
12651 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652 return (PyObject *)result;
12653
Benjamin Peterson29060642009-01-31 22:14:21 +000012654 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012656 Py_DECREF(uformat);
12657 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012658 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659 }
12660 return NULL;
12661}
12662
Jeremy Hylton938ace62002-07-17 16:30:39 +000012663static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000012664unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
12665
Tim Peters6d6c1a32001-08-02 04:15:00 +000012666static PyObject *
12667unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12668{
Benjamin Peterson29060642009-01-31 22:14:21 +000012669 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012670 static char *kwlist[] = {"object", "encoding", "errors", 0};
12671 char *encoding = NULL;
12672 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000012673
Benjamin Peterson14339b62009-01-31 16:36:08 +000012674 if (type != &PyUnicode_Type)
12675 return unicode_subtype_new(type, args, kwds);
12676 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000012677 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012678 return NULL;
12679 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012681 if (encoding == NULL && errors == NULL)
12682 return PyObject_Str(x);
12683 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012684 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000012685}
12686
Guido van Rossume023fe02001-08-30 03:12:59 +000012687static PyObject *
12688unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12689{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012690 PyUnicodeObject *unicode, *self;
12691 Py_ssize_t length, char_size;
12692 int share_wstr, share_utf8;
12693 unsigned int kind;
12694 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000012695
Benjamin Peterson14339b62009-01-31 16:36:08 +000012696 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012697
12698 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
12699 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012700 return NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012701 assert(PyUnicode_Check(unicode));
12702 if (PyUnicode_READY(unicode))
12703 return NULL;
12704
12705 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
12706 if (self == NULL) {
12707 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012708 return NULL;
12709 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012710 kind = PyUnicode_KIND(unicode);
12711 length = PyUnicode_GET_LENGTH(unicode);
12712
12713 _PyUnicode_LENGTH(self) = length;
12714 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
12715 _PyUnicode_STATE(self).interned = 0;
12716 _PyUnicode_STATE(self).kind = kind;
12717 _PyUnicode_STATE(self).compact = 0;
12718 _PyUnicode_STATE(self).ascii = 0;
12719 _PyUnicode_STATE(self).ready = 1;
12720 _PyUnicode_WSTR(self) = NULL;
12721 _PyUnicode_UTF8_LENGTH(self) = 0;
12722 _PyUnicode_UTF8(self) = NULL;
12723 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020012724 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012725
12726 share_utf8 = 0;
12727 share_wstr = 0;
12728 if (kind == PyUnicode_1BYTE_KIND) {
12729 char_size = 1;
12730 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
12731 share_utf8 = 1;
12732 }
12733 else if (kind == PyUnicode_2BYTE_KIND) {
12734 char_size = 2;
12735 if (sizeof(wchar_t) == 2)
12736 share_wstr = 1;
12737 }
12738 else {
12739 assert(kind == PyUnicode_4BYTE_KIND);
12740 char_size = 4;
12741 if (sizeof(wchar_t) == 4)
12742 share_wstr = 1;
12743 }
12744
12745 /* Ensure we won't overflow the length. */
12746 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
12747 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012749 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012750 data = PyObject_MALLOC((length + 1) * char_size);
12751 if (data == NULL) {
12752 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753 goto onError;
12754 }
12755
Victor Stinnerc3c74152011-10-02 20:39:55 +020012756 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012757 if (share_utf8) {
12758 _PyUnicode_UTF8_LENGTH(self) = length;
12759 _PyUnicode_UTF8(self) = data;
12760 }
12761 if (share_wstr) {
12762 _PyUnicode_WSTR_LENGTH(self) = length;
12763 _PyUnicode_WSTR(self) = (wchar_t *)data;
12764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012766 Py_MEMCPY(data, PyUnicode_DATA(unicode),
12767 PyUnicode_KIND_SIZE(kind, length + 1));
12768 Py_DECREF(unicode);
12769 return (PyObject *)self;
12770
12771onError:
12772 Py_DECREF(unicode);
12773 Py_DECREF(self);
12774 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000012775}
12776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012777PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000012779\n\
Collin Winterd474ce82007-08-07 19:42:11 +000012780Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000012781encoding defaults to the current default string encoding.\n\
12782errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000012783
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012784static PyObject *unicode_iter(PyObject *seq);
12785
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000012787 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012788 "str", /* tp_name */
12789 sizeof(PyUnicodeObject), /* tp_size */
12790 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012792 (destructor)unicode_dealloc, /* tp_dealloc */
12793 0, /* tp_print */
12794 0, /* tp_getattr */
12795 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012796 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012797 unicode_repr, /* tp_repr */
12798 &unicode_as_number, /* tp_as_number */
12799 &unicode_as_sequence, /* tp_as_sequence */
12800 &unicode_as_mapping, /* tp_as_mapping */
12801 (hashfunc) unicode_hash, /* tp_hash*/
12802 0, /* tp_call*/
12803 (reprfunc) unicode_str, /* tp_str */
12804 PyObject_GenericGetAttr, /* tp_getattro */
12805 0, /* tp_setattro */
12806 0, /* tp_as_buffer */
12807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012809 unicode_doc, /* tp_doc */
12810 0, /* tp_traverse */
12811 0, /* tp_clear */
12812 PyUnicode_RichCompare, /* tp_richcompare */
12813 0, /* tp_weaklistoffset */
12814 unicode_iter, /* tp_iter */
12815 0, /* tp_iternext */
12816 unicode_methods, /* tp_methods */
12817 0, /* tp_members */
12818 0, /* tp_getset */
12819 &PyBaseObject_Type, /* tp_base */
12820 0, /* tp_dict */
12821 0, /* tp_descr_get */
12822 0, /* tp_descr_set */
12823 0, /* tp_dictoffset */
12824 0, /* tp_init */
12825 0, /* tp_alloc */
12826 unicode_new, /* tp_new */
12827 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828};
12829
12830/* Initialize the Unicode implementation */
12831
Thomas Wouters78890102000-07-22 19:25:51 +000012832void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012834 int i;
12835
Thomas Wouters477c8d52006-05-27 19:21:47 +000012836 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012838 0x000A, /* LINE FEED */
12839 0x000D, /* CARRIAGE RETURN */
12840 0x001C, /* FILE SEPARATOR */
12841 0x001D, /* GROUP SEPARATOR */
12842 0x001E, /* RECORD SEPARATOR */
12843 0x0085, /* NEXT LINE */
12844 0x2028, /* LINE SEPARATOR */
12845 0x2029, /* PARAGRAPH SEPARATOR */
12846 };
12847
Fred Drakee4315f52000-05-09 19:53:39 +000012848 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020012849 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012850 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012852
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012853 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000012855 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012856 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857
12858 /* initialize the linebreak bloom filter */
12859 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012860 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020012861 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012862
12863 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012864}
12865
12866/* Finalize the Unicode implementation */
12867
Christian Heimesa156e092008-02-16 07:38:31 +000012868int
12869PyUnicode_ClearFreeList(void)
12870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000012872}
12873
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874void
Thomas Wouters78890102000-07-22 19:25:51 +000012875_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012876{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012877 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000012879 Py_XDECREF(unicode_empty);
12880 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000012881
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012882 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012883 if (unicode_latin1[i]) {
12884 Py_DECREF(unicode_latin1[i]);
12885 unicode_latin1[i] = NULL;
12886 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012887 }
Christian Heimesa156e092008-02-16 07:38:31 +000012888 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000012890
Walter Dörwald16807132007-05-25 13:52:07 +000012891void
12892PyUnicode_InternInPlace(PyObject **p)
12893{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012894 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
12895 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020012896#ifdef Py_DEBUG
12897 assert(s != NULL);
12898 assert(_PyUnicode_CHECK(s));
12899#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000012900 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020012901 return;
12902#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000012903 /* If it's a subclass, we don't really know what putting
12904 it in the interned dict might do. */
12905 if (!PyUnicode_CheckExact(s))
12906 return;
12907 if (PyUnicode_CHECK_INTERNED(s))
12908 return;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 if (PyUnicode_READY(s) == -1) {
Victor Stinner4fae54c2011-10-03 02:01:52 +020012910 assert(0 && "PyUnicode_READY fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012911 return;
12912 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012913 if (interned == NULL) {
12914 interned = PyDict_New();
12915 if (interned == NULL) {
12916 PyErr_Clear(); /* Don't leave an exception */
12917 return;
12918 }
12919 }
12920 /* It might be that the GetItem call fails even
12921 though the key is present in the dictionary,
12922 namely when this happens during a stack overflow. */
12923 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000012924 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012925 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000012926
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 if (t) {
12928 Py_INCREF(t);
12929 Py_DECREF(*p);
12930 *p = t;
12931 return;
12932 }
Walter Dörwald16807132007-05-25 13:52:07 +000012933
Benjamin Peterson14339b62009-01-31 16:36:08 +000012934 PyThreadState_GET()->recursion_critical = 1;
12935 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
12936 PyErr_Clear();
12937 PyThreadState_GET()->recursion_critical = 0;
12938 return;
12939 }
12940 PyThreadState_GET()->recursion_critical = 0;
12941 /* The two references in interned are not counted by refcnt.
12942 The deallocator will take care of this */
12943 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000012945}
12946
12947void
12948PyUnicode_InternImmortal(PyObject **p)
12949{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012950 PyUnicodeObject *u = (PyUnicodeObject *)*p;
12951
Benjamin Peterson14339b62009-01-31 16:36:08 +000012952 PyUnicode_InternInPlace(p);
12953 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012955 Py_INCREF(*p);
12956 }
Walter Dörwald16807132007-05-25 13:52:07 +000012957}
12958
12959PyObject *
12960PyUnicode_InternFromString(const char *cp)
12961{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012962 PyObject *s = PyUnicode_FromString(cp);
12963 if (s == NULL)
12964 return NULL;
12965 PyUnicode_InternInPlace(&s);
12966 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000012967}
12968
Alexander Belopolsky40018472011-02-26 01:02:56 +000012969void
12970_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000012971{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012972 PyObject *keys;
12973 PyUnicodeObject *s;
12974 Py_ssize_t i, n;
12975 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000012976
Benjamin Peterson14339b62009-01-31 16:36:08 +000012977 if (interned == NULL || !PyDict_Check(interned))
12978 return;
12979 keys = PyDict_Keys(interned);
12980 if (keys == NULL || !PyList_Check(keys)) {
12981 PyErr_Clear();
12982 return;
12983 }
Walter Dörwald16807132007-05-25 13:52:07 +000012984
Benjamin Peterson14339b62009-01-31 16:36:08 +000012985 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
12986 detector, interned unicode strings are not forcibly deallocated;
12987 rather, we give them their stolen references back, and then clear
12988 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000012989
Benjamin Peterson14339b62009-01-31 16:36:08 +000012990 n = PyList_GET_SIZE(keys);
12991 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000012992 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012993 for (i = 0; i < n; i++) {
12994 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012995 if (PyUnicode_READY(s) == -1)
12996 fprintf(stderr, "could not ready string\n");
12997 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012998 case SSTATE_NOT_INTERNED:
12999 /* XXX Shouldn't happen */
13000 break;
13001 case SSTATE_INTERNED_IMMORTAL:
13002 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013004 break;
13005 case SSTATE_INTERNED_MORTAL:
13006 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013008 break;
13009 default:
13010 Py_FatalError("Inconsistent interned string state.");
13011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013013 }
13014 fprintf(stderr, "total size of all interned strings: "
13015 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13016 "mortal/immortal\n", mortal_size, immortal_size);
13017 Py_DECREF(keys);
13018 PyDict_Clear(interned);
13019 Py_DECREF(interned);
13020 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013021}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013022
13023
13024/********************* Unicode Iterator **************************/
13025
13026typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013027 PyObject_HEAD
13028 Py_ssize_t it_index;
13029 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013030} unicodeiterobject;
13031
13032static void
13033unicodeiter_dealloc(unicodeiterobject *it)
13034{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013035 _PyObject_GC_UNTRACK(it);
13036 Py_XDECREF(it->it_seq);
13037 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013038}
13039
13040static int
13041unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13042{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013043 Py_VISIT(it->it_seq);
13044 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013045}
13046
13047static PyObject *
13048unicodeiter_next(unicodeiterobject *it)
13049{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013050 PyUnicodeObject *seq;
13051 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013052
Benjamin Peterson14339b62009-01-31 16:36:08 +000013053 assert(it != NULL);
13054 seq = it->it_seq;
13055 if (seq == NULL)
13056 return NULL;
13057 assert(PyUnicode_Check(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013059 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13060 int kind = PyUnicode_KIND(seq);
13061 void *data = PyUnicode_DATA(seq);
13062 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13063 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013064 if (item != NULL)
13065 ++it->it_index;
13066 return item;
13067 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013068
Benjamin Peterson14339b62009-01-31 16:36:08 +000013069 Py_DECREF(seq);
13070 it->it_seq = NULL;
13071 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013072}
13073
13074static PyObject *
13075unicodeiter_len(unicodeiterobject *it)
13076{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013077 Py_ssize_t len = 0;
13078 if (it->it_seq)
13079 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13080 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013081}
13082
13083PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13084
13085static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013086 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013087 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013088 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013089};
13090
13091PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13093 "str_iterator", /* tp_name */
13094 sizeof(unicodeiterobject), /* tp_basicsize */
13095 0, /* tp_itemsize */
13096 /* methods */
13097 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13098 0, /* tp_print */
13099 0, /* tp_getattr */
13100 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013101 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013102 0, /* tp_repr */
13103 0, /* tp_as_number */
13104 0, /* tp_as_sequence */
13105 0, /* tp_as_mapping */
13106 0, /* tp_hash */
13107 0, /* tp_call */
13108 0, /* tp_str */
13109 PyObject_GenericGetAttr, /* tp_getattro */
13110 0, /* tp_setattro */
13111 0, /* tp_as_buffer */
13112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13113 0, /* tp_doc */
13114 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13115 0, /* tp_clear */
13116 0, /* tp_richcompare */
13117 0, /* tp_weaklistoffset */
13118 PyObject_SelfIter, /* tp_iter */
13119 (iternextfunc)unicodeiter_next, /* tp_iternext */
13120 unicodeiter_methods, /* tp_methods */
13121 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013122};
13123
13124static PyObject *
13125unicode_iter(PyObject *seq)
13126{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013127 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013128
Benjamin Peterson14339b62009-01-31 16:36:08 +000013129 if (!PyUnicode_Check(seq)) {
13130 PyErr_BadInternalCall();
13131 return NULL;
13132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 if (PyUnicode_READY(seq) == -1)
13134 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013135 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13136 if (it == NULL)
13137 return NULL;
13138 it->it_index = 0;
13139 Py_INCREF(seq);
13140 it->it_seq = (PyUnicodeObject *)seq;
13141 _PyObject_GC_TRACK(it);
13142 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013143}
13144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145#define UNIOP(x) Py_UNICODE_##x
13146#define UNIOP_t Py_UNICODE
13147#include "uniops.h"
13148#undef UNIOP
13149#undef UNIOP_t
13150#define UNIOP(x) Py_UCS4_##x
13151#define UNIOP_t Py_UCS4
13152#include "uniops.h"
13153#undef UNIOP
13154#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013155
Victor Stinner71133ff2010-09-01 23:43:53 +000013156Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013157PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013158{
13159 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13160 Py_UNICODE *copy;
13161 Py_ssize_t size;
13162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013163 if (!PyUnicode_Check(unicode)) {
13164 PyErr_BadArgument();
13165 return NULL;
13166 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013167 /* Ensure we won't overflow the size. */
13168 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13169 PyErr_NoMemory();
13170 return NULL;
13171 }
13172 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13173 size *= sizeof(Py_UNICODE);
13174 copy = PyMem_Malloc(size);
13175 if (copy == NULL) {
13176 PyErr_NoMemory();
13177 return NULL;
13178 }
13179 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13180 return copy;
13181}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013182
Georg Brandl66c221e2010-10-14 07:04:07 +000013183/* A _string module, to export formatter_parser and formatter_field_name_split
13184 to the string.Formatter class implemented in Python. */
13185
13186static PyMethodDef _string_methods[] = {
13187 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13188 METH_O, PyDoc_STR("split the argument as a field name")},
13189 {"formatter_parser", (PyCFunction) formatter_parser,
13190 METH_O, PyDoc_STR("parse the argument as a format string")},
13191 {NULL, NULL}
13192};
13193
13194static struct PyModuleDef _string_module = {
13195 PyModuleDef_HEAD_INIT,
13196 "_string",
13197 PyDoc_STR("string helper module"),
13198 0,
13199 _string_methods,
13200 NULL,
13201 NULL,
13202 NULL,
13203 NULL
13204};
13205
13206PyMODINIT_FUNC
13207PyInit__string(void)
13208{
13209 return PyModule_Create(&_string_module);
13210}
13211
13212
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013213#ifdef __cplusplus
13214}
13215#endif