blob: 1d90f69be06deb74e59960c4572025248c76c58f [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 Stinner910337b2011-10-03 03:20:16 +020092#ifdef Py_DEBUG
93# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op)
94#else
95# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
96#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020097
Victor Stinnere90fe6a2011-10-01 16:48:13 +020098#define _PyUnicode_UTF8(op) \
99 (((PyCompactUnicodeObject*)(op))->utf8)
100#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200101 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102 assert(PyUnicode_IS_READY(op)), \
103 PyUnicode_IS_COMPACT_ASCII(op) ? \
104 ((char*)((PyASCIIObject*)(op) + 1)) : \
105 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200106#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200107 (((PyCompactUnicodeObject*)(op))->utf8_length)
108#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200109 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200110 assert(PyUnicode_IS_READY(op)), \
111 PyUnicode_IS_COMPACT_ASCII(op) ? \
112 ((PyASCIIObject*)(op))->length : \
113 _PyUnicode_UTF8_LENGTH(op))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200114#define _PyUnicode_WSTR(op) (((PyASCIIObject*)(op))->wstr)
115#define _PyUnicode_WSTR_LENGTH(op) (((PyCompactUnicodeObject*)(op))->wstr_length)
116#define _PyUnicode_LENGTH(op) (((PyASCIIObject *)(op))->length)
117#define _PyUnicode_STATE(op) (((PyASCIIObject *)(op))->state)
118#define _PyUnicode_HASH(op) (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200119#define _PyUnicode_KIND(op) \
120 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200121 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200122#define _PyUnicode_GET_LENGTH(op) \
123 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200124 ((PyASCIIObject *)(op))->length)
Victor Stinnerc3c74152011-10-02 20:39:55 +0200125#define _PyUnicode_DATA_ANY(op) (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200126
Victor Stinner910337b2011-10-03 03:20:16 +0200127#undef PyUnicode_READY
128#define PyUnicode_READY(op) \
129 (assert(_PyUnicode_CHECK(op)), \
130 (PyUnicode_IS_READY(op) ? \
131 0 : _PyUnicode_Ready((PyObject *)(op))))
132
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200133#define _PyUnicode_READY_REPLACE(p_obj) \
134 (assert(_PyUnicode_CHECK(*p_obj)), \
135 (PyUnicode_IS_READY(*p_obj) ? \
136 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
137
Victor Stinnerc379ead2011-10-03 12:52:27 +0200138#define _PyUnicode_SHARE_UTF8(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
141 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
142#define _PyUnicode_SHARE_WSTR(op) \
143 (assert(_PyUnicode_CHECK(op)), \
144 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
145
Victor Stinner829c0ad2011-10-03 01:08:02 +0200146/* true if the Unicode object has an allocated UTF-8 memory block
147 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200148#define _PyUnicode_HAS_UTF8_MEMORY(op) \
149 (assert(_PyUnicode_CHECK(op)), \
150 (!PyUnicode_IS_COMPACT_ASCII(op) \
151 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200152 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
153
Victor Stinner910337b2011-10-03 03:20:16 +0200154/* Generic helper macro to convert characters of different types.
155 from_type and to_type have to be valid type names, begin and end
156 are pointers to the source characters which should be of type
157 "from_type *". to is a pointer of type "to_type *" and points to the
158 buffer where the result characters are written to. */
159#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
160 do { \
161 const from_type *iter_; to_type *to_; \
162 for (iter_ = (begin), to_ = (to_type *)(to); \
163 iter_ < (end); \
164 ++iter_, ++to_) { \
165 *to_ = (to_type)*iter_; \
166 } \
167 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200168
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200169/* The Unicode string has been modified: reset the hash */
170#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
171
Walter Dörwald16807132007-05-25 13:52:07 +0000172/* This dictionary holds all interned unicode strings. Note that references
173 to strings in this dictionary are *not* counted in the string's ob_refcnt.
174 When the interned string reaches a refcnt of 0 the string deallocation
175 function will delete the reference from this dictionary.
176
177 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000178 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000179*/
180static PyObject *interned;
181
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000182/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200183static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000184
185/* Single character Unicode strings in the Latin-1 range are being
186 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200187static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000188
Christian Heimes190d79e2008-01-30 11:58:22 +0000189/* Fast detection of the most frequent whitespace characters */
190const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000192/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000193/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000C: * FORM FEED */
196/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000197 0, 1, 1, 1, 1, 1, 0, 0,
198 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000199/* case 0x001C: * FILE SEPARATOR */
200/* case 0x001D: * GROUP SEPARATOR */
201/* case 0x001E: * RECORD SEPARATOR */
202/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 1, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000209
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000218};
219
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200220/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200221static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200223
Alexander Belopolsky40018472011-02-26 01:02:56 +0000224static PyObject *
225unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000226 PyObject **errorHandler,const char *encoding, const char *reason,
227 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
228 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static void
231raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300232 const char *encoding,
233 const Py_UNICODE *unicode, Py_ssize_t size,
234 Py_ssize_t startpos, Py_ssize_t endpos,
235 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000236
Christian Heimes190d79e2008-01-30 11:58:22 +0000237/* Same for linebreaks */
238static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000239 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000240/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000241/* 0x000B, * LINE TABULATION */
242/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000243/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000244 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000245 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000246/* 0x001C, * FILE SEPARATOR */
247/* 0x001D, * GROUP SEPARATOR */
248/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000249 0, 0, 0, 0, 1, 1, 1, 0,
250 0, 0, 0, 0, 0, 0, 0, 0,
251 0, 0, 0, 0, 0, 0, 0, 0,
252 0, 0, 0, 0, 0, 0, 0, 0,
253 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000254
Benjamin Peterson14339b62009-01-31 16:36:08 +0000255 0, 0, 0, 0, 0, 0, 0, 0,
256 0, 0, 0, 0, 0, 0, 0, 0,
257 0, 0, 0, 0, 0, 0, 0, 0,
258 0, 0, 0, 0, 0, 0, 0, 0,
259 0, 0, 0, 0, 0, 0, 0, 0,
260 0, 0, 0, 0, 0, 0, 0, 0,
261 0, 0, 0, 0, 0, 0, 0, 0,
262 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000263};
264
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300265/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
266 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000267Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000268PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000269{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000270#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000271 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000272#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 /* This is actually an illegal character, so it should
274 not be passed to unichr. */
275 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000276#endif
277}
278
Victor Stinner910337b2011-10-03 03:20:16 +0200279#ifdef Py_DEBUG
280static int
281_PyUnicode_CheckConsistency(void *op)
282{
283 PyASCIIObject *ascii;
284 unsigned int kind;
285
286 assert(PyUnicode_Check(op));
287
288 ascii = (PyASCIIObject *)op;
289 kind = ascii->state.kind;
290
Victor Stinnera3b334d2011-10-03 13:53:37 +0200291 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200292 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200293 assert(ascii->state.ready == 1);
294 }
295 else if (ascii->state.compact == 1) {
Victor Stinner85041a52011-10-03 14:42:39 +0200296 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner910337b2011-10-03 03:20:16 +0200297 assert(kind == PyUnicode_1BYTE_KIND
298 || kind == PyUnicode_2BYTE_KIND
299 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200300 assert(ascii->state.ascii == 0);
301 assert(ascii->state.ready == 1);
Victor Stinner85041a52011-10-03 14:42:39 +0200302 assert (compact->utf8 != (void*)(compact + 1));
Victor Stinner910337b2011-10-03 03:20:16 +0200303 } else {
304 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
305 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
306
307 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnera3b334d2011-10-03 13:53:37 +0200308 assert(ascii->state.compact == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200309 assert(ascii->state.ascii == 0);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200310 assert(ascii->state.ready == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200311 assert(ascii->wstr != NULL);
312 assert(unicode->data.any == NULL);
313 assert(compact->utf8 == NULL);
314 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
315 }
316 else {
317 assert(kind == PyUnicode_1BYTE_KIND
318 || kind == PyUnicode_2BYTE_KIND
319 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200320 assert(ascii->state.compact == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 assert(unicode->data.any != NULL);
Victor Stinner85041a52011-10-03 14:42:39 +0200323 if (ascii->state.ascii)
324 assert (compact->utf8 == unicode->data.any);
325 else
326 assert (compact->utf8 != unicode->data.any);
Victor Stinner910337b2011-10-03 03:20:16 +0200327 }
328 }
329 return 1;
330}
331#endif
332
Thomas Wouters477c8d52006-05-27 19:21:47 +0000333/* --- Bloom Filters ----------------------------------------------------- */
334
335/* stuff to implement simple "bloom filters" for Unicode characters.
336 to keep things simple, we use a single bitmask, using the least 5
337 bits from each unicode characters as the bit index. */
338
339/* the linebreak mask is set up by Unicode_Init below */
340
Antoine Pitrouf068f942010-01-13 14:19:12 +0000341#if LONG_BIT >= 128
342#define BLOOM_WIDTH 128
343#elif LONG_BIT >= 64
344#define BLOOM_WIDTH 64
345#elif LONG_BIT >= 32
346#define BLOOM_WIDTH 32
347#else
348#error "LONG_BIT is smaller than 32"
349#endif
350
Thomas Wouters477c8d52006-05-27 19:21:47 +0000351#define BLOOM_MASK unsigned long
352
353static BLOOM_MASK bloom_linebreak;
354
Antoine Pitrouf068f942010-01-13 14:19:12 +0000355#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
356#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357
Benjamin Peterson29060642009-01-31 22:14:21 +0000358#define BLOOM_LINEBREAK(ch) \
359 ((ch) < 128U ? ascii_linebreak[(ch)] : \
360 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361
Alexander Belopolsky40018472011-02-26 01:02:56 +0000362Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200363make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000364{
365 /* calculate simple bloom-style bitmask for a given unicode string */
366
Antoine Pitrouf068f942010-01-13 14:19:12 +0000367 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368 Py_ssize_t i;
369
370 mask = 0;
371 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200372 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373
374 return mask;
375}
376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200377#define BLOOM_MEMBER(mask, chr, str) \
378 (BLOOM(mask, chr) \
379 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000380
Guido van Rossumd57fd912000-03-10 22:53:23 +0000381/* --- Unicode Object ----------------------------------------------------- */
382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200383static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200384fixup(PyUnicodeObject *self, Py_UCS4 (*fixfct)(PyUnicodeObject *s));
385
386Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
387 Py_ssize_t size, Py_UCS4 ch,
388 int direction)
389{
390 /* like wcschr, but doesn't stop at NULL characters */
391 Py_ssize_t i;
392 if (direction == 1) {
393 for(i = 0; i < size; i++)
394 if (PyUnicode_READ(kind, s, i) == ch)
395 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
396 }
397 else {
398 for(i = size-1; i >= 0; i--)
399 if (PyUnicode_READ(kind, s, i) == ch)
400 return (char*)s + PyUnicode_KIND_SIZE(kind, i);
401 }
402 return NULL;
403}
404
Victor Stinnerfe226c02011-10-03 03:52:20 +0200405static PyObject*
406resize_compact(PyObject *unicode, Py_ssize_t length)
407{
408 Py_ssize_t char_size;
409 Py_ssize_t struct_size;
410 Py_ssize_t new_size;
411 int share_wstr;
412
413 assert(PyUnicode_IS_READY(unicode));
414 char_size = PyUnicode_CHARACTER_SIZE(unicode);
415 if (PyUnicode_IS_COMPACT_ASCII(unicode))
416 struct_size = sizeof(PyASCIIObject);
417 else
418 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200419 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200420
421 _Py_DEC_REFTOTAL;
422 _Py_ForgetReference(unicode);
423
424 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
425 PyErr_NoMemory();
426 return NULL;
427 }
428 new_size = (struct_size + (length + 1) * char_size);
429
430 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
431 if (unicode == NULL) {
432 PyObject_Del(unicode);
433 PyErr_NoMemory();
434 return NULL;
435 }
436 _Py_NewReference(unicode);
437 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200438 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200439 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200440 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
441 _PyUnicode_WSTR_LENGTH(unicode) = length;
442 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200443 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
444 length, 0);
445 return unicode;
446}
447
Alexander Belopolsky40018472011-02-26 01:02:56 +0000448static int
Victor Stinnerfe226c02011-10-03 03:52:20 +0200449resize_inplace(register PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000450{
451 void *oldstr;
Tim Petersced69f82003-09-16 20:30:58 +0000452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200453 assert(!PyUnicode_IS_COMPACT(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454
Victor Stinnerfe226c02011-10-03 03:52:20 +0200455 assert(Py_REFCNT(unicode) == 1);
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200456 _PyUnicode_DIRTY(unicode);
Tim Petersced69f82003-09-16 20:30:58 +0000457
Victor Stinnerfe226c02011-10-03 03:52:20 +0200458 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
459 {
460 PyObject_DEL(_PyUnicode_UTF8(unicode));
461 _PyUnicode_UTF8(unicode) = NULL;
462 }
463
464 if (PyUnicode_IS_READY(unicode)) {
465 Py_ssize_t char_size;
466 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200467 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200468 void *data;
469
470 data = _PyUnicode_DATA_ANY(unicode);
471 assert(data != NULL);
472 char_size = PyUnicode_CHARACTER_SIZE(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200473 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
474 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200475
476 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
477 PyErr_NoMemory();
478 return -1;
479 }
480 new_size = (length + 1) * char_size;
481
482 data = (PyObject *)PyObject_REALLOC(data, new_size);
483 if (data == NULL) {
484 PyErr_NoMemory();
485 return -1;
486 }
487 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200488 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200489 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200490 _PyUnicode_WSTR_LENGTH(unicode) = length;
491 }
492 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200493 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200494 _PyUnicode_UTF8_LENGTH(unicode) = length;
495 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200496 _PyUnicode_LENGTH(unicode) = length;
497 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
498 if (share_wstr)
499 return 0;
500 }
501 if (_PyUnicode_WSTR(unicode) != NULL) {
502 assert(_PyUnicode_WSTR(unicode) != NULL);
503
504 oldstr = _PyUnicode_WSTR(unicode);
505 _PyUnicode_WSTR(unicode) = PyObject_REALLOC(_PyUnicode_WSTR(unicode),
506 sizeof(Py_UNICODE) * (length + 1));
507 if (!_PyUnicode_WSTR(unicode)) {
508 _PyUnicode_WSTR(unicode) = (Py_UNICODE *)oldstr;
509 PyErr_NoMemory();
510 return -1;
511 }
512 _PyUnicode_WSTR(unicode)[length] = 0;
513 _PyUnicode_WSTR_LENGTH(unicode) = length;
514 }
Guido van Rossumd57fd912000-03-10 22:53:23 +0000515 return 0;
516}
517
Victor Stinnerfe226c02011-10-03 03:52:20 +0200518static PyObject*
519resize_copy(PyObject *unicode, Py_ssize_t length)
520{
521 Py_ssize_t copy_length;
522 if (PyUnicode_IS_COMPACT(unicode)) {
523 PyObject *copy;
524 assert(PyUnicode_IS_READY(unicode));
525
526 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
527 if (copy == NULL)
528 return NULL;
529
530 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
531 if (PyUnicode_CopyCharacters(copy, 0,
532 unicode, 0,
533 copy_length) < 0)
534 {
535 Py_DECREF(copy);
536 return NULL;
537 }
538 return copy;
539 } else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200540 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200541 assert(_PyUnicode_WSTR(unicode) != NULL);
542 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200543 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200544 if (w == NULL)
545 return NULL;
546 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
547 copy_length = Py_MIN(copy_length, length);
548 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
549 copy_length);
550 return (PyObject*)w;
551 }
552}
553
Guido van Rossumd57fd912000-03-10 22:53:23 +0000554/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000555 Ux0000 terminated; some code (e.g. new_identifier)
556 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000557
558 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000559 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000560
561*/
562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200563#ifdef Py_DEBUG
564int unicode_old_new_calls = 0;
565#endif
566
Alexander Belopolsky40018472011-02-26 01:02:56 +0000567static PyUnicodeObject *
568_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000569{
570 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200571 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000572
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000574 if (length == 0 && unicode_empty != NULL) {
575 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200576 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000577 }
578
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000579 /* Ensure we won't overflow the size. */
580 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
581 return (PyUnicodeObject *)PyErr_NoMemory();
582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200583 if (length < 0) {
584 PyErr_SetString(PyExc_SystemError,
585 "Negative size passed to _PyUnicode_New");
586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000587 }
588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200589#ifdef Py_DEBUG
590 ++unicode_old_new_calls;
591#endif
592
593 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
594 if (unicode == NULL)
595 return NULL;
596 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
597 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
598 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000599 PyErr_NoMemory();
600 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000601 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200602
Jeremy Hyltond8082792003-09-16 19:41:39 +0000603 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000604 * the caller fails before initializing str -- unicode_resize()
605 * reads str[0], and the Keep-Alive optimization can keep memory
606 * allocated for str alive across a call to unicode_dealloc(unicode).
607 * We don't want unicode_resize to read uninitialized memory in
608 * that case.
609 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200610 _PyUnicode_WSTR(unicode)[0] = 0;
611 _PyUnicode_WSTR(unicode)[length] = 0;
612 _PyUnicode_WSTR_LENGTH(unicode) = length;
613 _PyUnicode_HASH(unicode) = -1;
614 _PyUnicode_STATE(unicode).interned = 0;
615 _PyUnicode_STATE(unicode).kind = 0;
616 _PyUnicode_STATE(unicode).compact = 0;
617 _PyUnicode_STATE(unicode).ready = 0;
618 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200619 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200620 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200621 _PyUnicode_UTF8(unicode) = NULL;
622 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000623 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000624
Benjamin Peterson29060642009-01-31 22:14:21 +0000625 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000626 /* XXX UNREF/NEWREF interface should be more symmetrical */
627 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000628 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000629 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000630 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000631}
632
Victor Stinnerf42dc442011-10-02 23:33:16 +0200633static const char*
634unicode_kind_name(PyObject *unicode)
635{
Victor Stinner42dfd712011-10-03 14:41:45 +0200636 /* don't check consistency: unicode_kind_name() is called from
637 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200638 if (!PyUnicode_IS_COMPACT(unicode))
639 {
640 if (!PyUnicode_IS_READY(unicode))
641 return "wstr";
642 switch(PyUnicode_KIND(unicode))
643 {
644 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200645 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200646 return "legacy ascii";
647 else
648 return "legacy latin1";
649 case PyUnicode_2BYTE_KIND:
650 return "legacy UCS2";
651 case PyUnicode_4BYTE_KIND:
652 return "legacy UCS4";
653 default:
654 return "<legacy invalid kind>";
655 }
656 }
657 assert(PyUnicode_IS_READY(unicode));
658 switch(PyUnicode_KIND(unicode))
659 {
660 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200661 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200662 return "ascii";
663 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200664 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200665 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200666 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200667 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200668 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200669 default:
670 return "<invalid compact kind>";
671 }
672}
673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200674#ifdef Py_DEBUG
675int unicode_new_new_calls = 0;
676
677/* Functions wrapping macros for use in debugger */
678char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200679 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200680}
681
682void *_PyUnicode_compact_data(void *unicode) {
683 return _PyUnicode_COMPACT_DATA(unicode);
684}
685void *_PyUnicode_data(void *unicode){
686 printf("obj %p\n", unicode);
687 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
688 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
689 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
690 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
691 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
692 return PyUnicode_DATA(unicode);
693}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200694
695void
696_PyUnicode_Dump(PyObject *op)
697{
698 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200699 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
700 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
701 void *data;
702 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
703 if (ascii->state.compact)
704 data = (compact + 1);
705 else
706 data = unicode->data.any;
707 if (ascii->wstr == data)
708 printf("shared ");
709 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200710 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200711 printf(" (%zu), ", compact->wstr_length);
712 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
713 printf("shared ");
714 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200715 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200716 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200717}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200718#endif
719
720PyObject *
721PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
722{
723 PyObject *obj;
724 PyCompactUnicodeObject *unicode;
725 void *data;
726 int kind_state;
727 int is_sharing = 0, is_ascii = 0;
728 Py_ssize_t char_size;
729 Py_ssize_t struct_size;
730
731 /* Optimization for empty strings */
732 if (size == 0 && unicode_empty != NULL) {
733 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200734 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200735 }
736
737#ifdef Py_DEBUG
738 ++unicode_new_new_calls;
739#endif
740
741 struct_size = sizeof(PyCompactUnicodeObject);
742 if (maxchar < 128) {
743 kind_state = PyUnicode_1BYTE_KIND;
744 char_size = 1;
745 is_ascii = 1;
746 struct_size = sizeof(PyASCIIObject);
747 }
748 else if (maxchar < 256) {
749 kind_state = PyUnicode_1BYTE_KIND;
750 char_size = 1;
751 }
752 else if (maxchar < 65536) {
753 kind_state = PyUnicode_2BYTE_KIND;
754 char_size = 2;
755 if (sizeof(wchar_t) == 2)
756 is_sharing = 1;
757 }
758 else {
759 kind_state = PyUnicode_4BYTE_KIND;
760 char_size = 4;
761 if (sizeof(wchar_t) == 4)
762 is_sharing = 1;
763 }
764
765 /* Ensure we won't overflow the size. */
766 if (size < 0) {
767 PyErr_SetString(PyExc_SystemError,
768 "Negative size passed to PyUnicode_New");
769 return NULL;
770 }
771 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
772 return PyErr_NoMemory();
773
774 /* Duplicated allocation code from _PyObject_New() instead of a call to
775 * PyObject_New() so we are able to allocate space for the object and
776 * it's data buffer.
777 */
778 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
779 if (obj == NULL)
780 return PyErr_NoMemory();
781 obj = PyObject_INIT(obj, &PyUnicode_Type);
782 if (obj == NULL)
783 return NULL;
784
785 unicode = (PyCompactUnicodeObject *)obj;
786 if (is_ascii)
787 data = ((PyASCIIObject*)obj) + 1;
788 else
789 data = unicode + 1;
790 _PyUnicode_LENGTH(unicode) = size;
791 _PyUnicode_HASH(unicode) = -1;
792 _PyUnicode_STATE(unicode).interned = 0;
793 _PyUnicode_STATE(unicode).kind = kind_state;
794 _PyUnicode_STATE(unicode).compact = 1;
795 _PyUnicode_STATE(unicode).ready = 1;
796 _PyUnicode_STATE(unicode).ascii = is_ascii;
797 if (is_ascii) {
798 ((char*)data)[size] = 0;
799 _PyUnicode_WSTR(unicode) = NULL;
800 }
801 else if (kind_state == PyUnicode_1BYTE_KIND) {
802 ((char*)data)[size] = 0;
803 _PyUnicode_WSTR(unicode) = NULL;
804 _PyUnicode_WSTR_LENGTH(unicode) = 0;
805 unicode->utf8_length = 0;
806 unicode->utf8 = NULL;
807 }
808 else {
809 unicode->utf8 = NULL;
810 if (kind_state == PyUnicode_2BYTE_KIND)
811 ((Py_UCS2*)data)[size] = 0;
812 else /* kind_state == PyUnicode_4BYTE_KIND */
813 ((Py_UCS4*)data)[size] = 0;
814 if (is_sharing) {
815 _PyUnicode_WSTR_LENGTH(unicode) = size;
816 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
817 }
818 else {
819 _PyUnicode_WSTR_LENGTH(unicode) = 0;
820 _PyUnicode_WSTR(unicode) = NULL;
821 }
822 }
823 return obj;
824}
825
826#if SIZEOF_WCHAR_T == 2
827/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
828 will decode surrogate pairs, the other conversions are implemented as macros
829 for efficency.
830
831 This function assumes that unicode can hold one more code point than wstr
832 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200833static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200834unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
835 PyUnicodeObject *unicode)
836{
837 const wchar_t *iter;
838 Py_UCS4 *ucs4_out;
839
Victor Stinner910337b2011-10-03 03:20:16 +0200840 assert(unicode != NULL);
841 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200842 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
843 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
844
845 for (iter = begin; iter < end; ) {
846 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
847 _PyUnicode_GET_LENGTH(unicode)));
848 if (*iter >= 0xD800 && *iter <= 0xDBFF
849 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
850 {
851 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
852 iter += 2;
853 }
854 else {
855 *ucs4_out++ = *iter;
856 iter++;
857 }
858 }
859 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
860 _PyUnicode_GET_LENGTH(unicode)));
861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200862}
863#endif
864
Victor Stinnercd9950f2011-10-02 00:34:53 +0200865static int
866_PyUnicode_Dirty(PyObject *unicode)
867{
Victor Stinner910337b2011-10-03 03:20:16 +0200868 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +0200869 if (Py_REFCNT(unicode) != 1) {
870 PyErr_SetString(PyExc_ValueError,
871 "Cannot modify a string having more than 1 reference");
872 return -1;
873 }
874 _PyUnicode_DIRTY(unicode);
875 return 0;
876}
877
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200878Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200879PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
880 PyObject *from, Py_ssize_t from_start,
881 Py_ssize_t how_many)
882{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200883 unsigned int from_kind, to_kind;
884 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200885
Victor Stinnerb1536152011-09-30 02:26:10 +0200886 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
887 PyErr_BadInternalCall();
888 return -1;
889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200890
891 if (PyUnicode_READY(from))
892 return -1;
893 if (PyUnicode_READY(to))
894 return -1;
895
Victor Stinnerff9e50f2011-09-28 22:17:19 +0200896 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200897 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
898 PyErr_Format(PyExc_ValueError,
899 "Cannot write %zi characters at %zi "
900 "in a string of %zi characters",
901 how_many, to_start, PyUnicode_GET_LENGTH(to));
902 return -1;
903 }
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200904 if (how_many == 0)
905 return 0;
906
Victor Stinnercd9950f2011-10-02 00:34:53 +0200907 if (_PyUnicode_Dirty(to))
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200908 return -1;
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200910 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200911 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200913 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200914
Victor Stinnerf42dc442011-10-02 23:33:16 +0200915 if (from_kind == to_kind
916 /* deny latin1 => ascii */
917 && PyUnicode_MAX_CHAR_VALUE(to) >= PyUnicode_MAX_CHAR_VALUE(from))
918 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200919 Py_MEMCPY((char*)to_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200920 + PyUnicode_KIND_SIZE(to_kind, to_start),
Victor Stinnera0702ab2011-09-29 14:14:38 +0200921 (char*)from_data
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200922 + PyUnicode_KIND_SIZE(from_kind, from_start),
923 PyUnicode_KIND_SIZE(to_kind, how_many));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200924 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200925 else if (from_kind == PyUnicode_1BYTE_KIND
926 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200927 {
928 _PyUnicode_CONVERT_BYTES(
929 Py_UCS1, Py_UCS2,
930 PyUnicode_1BYTE_DATA(from) + from_start,
931 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
932 PyUnicode_2BYTE_DATA(to) + to_start
933 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200934 }
Victor Stinner157f83f2011-09-28 21:41:31 +0200935 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200936 && to_kind == PyUnicode_4BYTE_KIND)
937 {
938 _PyUnicode_CONVERT_BYTES(
939 Py_UCS1, Py_UCS4,
940 PyUnicode_1BYTE_DATA(from) + from_start,
941 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
942 PyUnicode_4BYTE_DATA(to) + to_start
943 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200944 }
945 else if (from_kind == PyUnicode_2BYTE_KIND
946 && to_kind == PyUnicode_4BYTE_KIND)
947 {
948 _PyUnicode_CONVERT_BYTES(
949 Py_UCS2, Py_UCS4,
950 PyUnicode_2BYTE_DATA(from) + from_start,
951 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
952 PyUnicode_4BYTE_DATA(to) + to_start
953 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +0200954 }
Victor Stinnera0702ab2011-09-29 14:14:38 +0200955 else {
956 int invalid_kinds;
Victor Stinnerf42dc442011-10-02 23:33:16 +0200957
958 /* check if max_char(from substring) <= max_char(to) */
959 if (from_kind > to_kind
960 /* latin1 => ascii */
Victor Stinnera3b334d2011-10-03 13:53:37 +0200961 || (PyUnicode_IS_ASCII(to)
Victor Stinnerf42dc442011-10-02 23:33:16 +0200962 && to_kind == PyUnicode_1BYTE_KIND
Victor Stinnera3b334d2011-10-03 13:53:37 +0200963 && !PyUnicode_IS_ASCII(from)))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 {
Victor Stinnera0702ab2011-09-29 14:14:38 +0200965 /* slow path to check for character overflow */
966 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
967 Py_UCS4 ch, maxchar;
968 Py_ssize_t i;
969
970 maxchar = 0;
971 invalid_kinds = 0;
972 for (i=0; i < how_many; i++) {
973 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
974 if (ch > maxchar) {
975 maxchar = ch;
976 if (maxchar > to_maxchar) {
977 invalid_kinds = 1;
978 break;
979 }
980 }
981 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
982 }
983 }
984 else
985 invalid_kinds = 1;
986 if (invalid_kinds) {
987 PyErr_Format(PyExc_ValueError,
Victor Stinnerf42dc442011-10-02 23:33:16 +0200988 "Cannot copy %s characters "
989 "into a string of %s characters",
990 unicode_kind_name(from),
991 unicode_kind_name(to));
Victor Stinnera0702ab2011-09-29 14:14:38 +0200992 return -1;
993 }
994 }
995 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996}
997
Victor Stinner17222162011-09-28 22:15:37 +0200998/* Find the maximum code point and count the number of surrogate pairs so a
999 correct string length can be computed before converting a string to UCS4.
1000 This function counts single surrogates as a character and not as a pair.
1001
1002 Return 0 on success, or -1 on error. */
1003static int
1004find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1005 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006{
1007 const wchar_t *iter;
1008
Victor Stinnerc53be962011-10-02 21:33:54 +02001009 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001010 if (num_surrogates == NULL || maxchar == NULL) {
1011 PyErr_SetString(PyExc_SystemError,
1012 "unexpected NULL arguments to "
1013 "PyUnicode_FindMaxCharAndNumSurrogatePairs");
1014 return -1;
1015 }
1016
1017 *num_surrogates = 0;
1018 *maxchar = 0;
1019
1020 for (iter = begin; iter < end; ) {
1021 if (*iter > *maxchar)
1022 *maxchar = *iter;
1023#if SIZEOF_WCHAR_T == 2
1024 if (*iter >= 0xD800 && *iter <= 0xDBFF
1025 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1026 {
1027 Py_UCS4 surrogate_val;
1028 surrogate_val = (((iter[0] & 0x3FF)<<10)
1029 | (iter[1] & 0x3FF)) + 0x10000;
1030 ++(*num_surrogates);
1031 if (surrogate_val > *maxchar)
1032 *maxchar = surrogate_val;
1033 iter += 2;
1034 }
1035 else
1036 iter++;
1037#else
1038 iter++;
1039#endif
1040 }
1041 return 0;
1042}
1043
1044#ifdef Py_DEBUG
1045int unicode_ready_calls = 0;
1046#endif
1047
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001048static int
1049unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001051 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 wchar_t *end;
1053 Py_UCS4 maxchar = 0;
1054 Py_ssize_t num_surrogates;
1055#if SIZEOF_WCHAR_T == 2
1056 Py_ssize_t length_wo_surrogates;
1057#endif
1058
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001059 assert(p_obj != NULL);
1060 unicode = (PyUnicodeObject *)*p_obj;
1061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062 /* _PyUnicode_Ready() is only intented for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001063 strings were created using _PyObject_New() and where no canonical
1064 representation (the str field) has been set yet aka strings
1065 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001066 assert(_PyUnicode_CHECK(unicode));
1067 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001069 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001070 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001071 /* Actually, it should neither be interned nor be anything else: */
1072 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073
1074#ifdef Py_DEBUG
1075 ++unicode_ready_calls;
1076#endif
1077
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001078#ifdef Py_DEBUG
1079 assert(!replace || Py_REFCNT(unicode) == 1);
1080#else
1081 if (replace && Py_REFCNT(unicode) != 1)
1082 replace = 0;
1083#endif
1084 if (replace) {
1085 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1086 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1087 /* Optimization for empty strings */
1088 if (len == 0) {
1089 Py_INCREF(unicode_empty);
1090 Py_DECREF(*p_obj);
1091 *p_obj = unicode_empty;
1092 return 0;
1093 }
1094 if (len == 1 && wstr[0] < 256) {
1095 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1096 if (latin1_char == NULL)
1097 return -1;
1098 Py_DECREF(*p_obj);
1099 *p_obj = latin1_char;
1100 return 0;
1101 }
1102 }
1103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001105 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001106 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108
1109 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001110 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1111 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112 PyErr_NoMemory();
1113 return -1;
1114 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001115 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 _PyUnicode_WSTR(unicode), end,
1117 PyUnicode_1BYTE_DATA(unicode));
1118 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1119 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1120 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1121 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001122 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001123 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001124 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 }
1126 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001127 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001128 _PyUnicode_UTF8(unicode) = NULL;
1129 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130 }
1131 PyObject_FREE(_PyUnicode_WSTR(unicode));
1132 _PyUnicode_WSTR(unicode) = NULL;
1133 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1134 }
1135 /* In this case we might have to convert down from 4-byte native
1136 wchar_t to 2-byte unicode. */
1137 else if (maxchar < 65536) {
1138 assert(num_surrogates == 0 &&
1139 "FindMaxCharAndNumSurrogatePairs() messed up");
1140
Victor Stinner506f5922011-09-28 22:34:18 +02001141#if SIZEOF_WCHAR_T == 2
1142 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001143 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001144 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1145 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1146 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001147 _PyUnicode_UTF8(unicode) = NULL;
1148 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001149#else
1150 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001151 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001152 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001153 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001154 PyErr_NoMemory();
1155 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156 }
Victor Stinner506f5922011-09-28 22:34:18 +02001157 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1158 _PyUnicode_WSTR(unicode), end,
1159 PyUnicode_2BYTE_DATA(unicode));
1160 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1161 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1162 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001163 _PyUnicode_UTF8(unicode) = NULL;
1164 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001165 PyObject_FREE(_PyUnicode_WSTR(unicode));
1166 _PyUnicode_WSTR(unicode) = NULL;
1167 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1168#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169 }
1170 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1171 else {
1172#if SIZEOF_WCHAR_T == 2
1173 /* in case the native representation is 2-bytes, we need to allocate a
1174 new normalized 4-byte version. */
1175 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001176 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1177 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 PyErr_NoMemory();
1179 return -1;
1180 }
1181 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1182 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001183 _PyUnicode_UTF8(unicode) = NULL;
1184 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001185 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1186 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001187 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001188 PyObject_FREE(_PyUnicode_WSTR(unicode));
1189 _PyUnicode_WSTR(unicode) = NULL;
1190 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1191#else
1192 assert(num_surrogates == 0);
1193
Victor Stinnerc3c74152011-10-02 20:39:55 +02001194 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001195 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001196 _PyUnicode_UTF8(unicode) = NULL;
1197 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1199#endif
1200 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1201 }
1202 _PyUnicode_STATE(unicode).ready = 1;
1203 return 0;
1204}
1205
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001206int
1207_PyUnicode_ReadyReplace(PyObject **op)
1208{
1209 return unicode_ready(op, 1);
1210}
1211
1212int
1213_PyUnicode_Ready(PyObject *op)
1214{
1215 return unicode_ready(&op, 0);
1216}
1217
Alexander Belopolsky40018472011-02-26 01:02:56 +00001218static void
1219unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001220{
Walter Dörwald16807132007-05-25 13:52:07 +00001221 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001222 case SSTATE_NOT_INTERNED:
1223 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001224
Benjamin Peterson29060642009-01-31 22:14:21 +00001225 case SSTATE_INTERNED_MORTAL:
1226 /* revive dead object temporarily for DelItem */
1227 Py_REFCNT(unicode) = 3;
1228 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1229 Py_FatalError(
1230 "deletion of interned string failed");
1231 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001232
Benjamin Peterson29060642009-01-31 22:14:21 +00001233 case SSTATE_INTERNED_IMMORTAL:
1234 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001235
Benjamin Peterson29060642009-01-31 22:14:21 +00001236 default:
1237 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001238 }
1239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001240 if (_PyUnicode_WSTR(unicode) &&
1241 (!PyUnicode_IS_READY(unicode) ||
1242 _PyUnicode_WSTR(unicode) != PyUnicode_DATA(unicode)))
1243 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001244 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001245 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001246
1247 if (PyUnicode_IS_COMPACT(unicode)) {
1248 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001249 }
1250 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001251 if (_PyUnicode_DATA_ANY(unicode))
1252 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001253 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001254 }
1255}
1256
Alexander Belopolsky40018472011-02-26 01:02:56 +00001257static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001258unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001259{
Victor Stinnera3be6132011-10-03 02:16:37 +02001260 Py_ssize_t len;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001261 if (Py_REFCNT(unicode) != 1)
1262 return 0;
1263 if (PyUnicode_CHECK_INTERNED(unicode))
1264 return 0;
1265 if (unicode == unicode_empty)
1266 return 0;
Victor Stinnera3be6132011-10-03 02:16:37 +02001267 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
1268 len = PyUnicode_WSTR_LENGTH(unicode);
1269 else
1270 len = PyUnicode_GET_LENGTH(unicode);
1271 if (len == 1) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001272 Py_UCS4 ch;
Victor Stinnera3be6132011-10-03 02:16:37 +02001273 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001274 ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnera3be6132011-10-03 02:16:37 +02001275 else
1276 ch = PyUnicode_READ_CHAR(unicode, 0);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001277 if (ch < 256 && unicode_latin1[ch] == unicode)
1278 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001279 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001280 return 1;
1281}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001282
Victor Stinnerfe226c02011-10-03 03:52:20 +02001283static int
1284unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1285{
1286 PyObject *unicode;
1287 Py_ssize_t old_length;
1288
1289 assert(p_unicode != NULL);
1290 unicode = *p_unicode;
1291
1292 assert(unicode != NULL);
1293 assert(PyUnicode_Check(unicode));
1294 assert(0 <= length);
1295
Victor Stinner910337b2011-10-03 03:20:16 +02001296 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001297 old_length = PyUnicode_WSTR_LENGTH(unicode);
1298 else
1299 old_length = PyUnicode_GET_LENGTH(unicode);
1300 if (old_length == length)
1301 return 0;
1302
1303 /* FIXME: really create a new object? */
1304 if (!unicode_resizable(unicode)) {
1305 PyObject *copy = resize_copy(unicode, length);
1306 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001307 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001308 Py_DECREF(*p_unicode);
1309 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001310 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001311 }
1312
Victor Stinnerfe226c02011-10-03 03:52:20 +02001313 if (PyUnicode_IS_COMPACT(unicode)) {
1314 *p_unicode = resize_compact(unicode, length);
1315 if (*p_unicode == NULL)
1316 return -1;
1317 return 0;
1318 } else
1319 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001320}
1321
Alexander Belopolsky40018472011-02-26 01:02:56 +00001322int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001323PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001324{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001325 PyObject *unicode;
1326 if (p_unicode == NULL) {
1327 PyErr_BadInternalCall();
1328 return -1;
1329 }
1330 unicode = *p_unicode;
1331 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1332 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1333 {
1334 PyErr_BadInternalCall();
1335 return -1;
1336 }
1337 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001338}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340static PyObject*
1341get_latin1_char(unsigned char ch)
1342{
Victor Stinnera464fc12011-10-02 20:39:30 +02001343 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001345 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346 if (!unicode)
1347 return NULL;
1348 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
1349 unicode_latin1[ch] = unicode;
1350 }
1351 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001352 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353}
1354
Alexander Belopolsky40018472011-02-26 01:02:56 +00001355PyObject *
1356PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001357{
1358 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001359 Py_UCS4 maxchar = 0;
1360 Py_ssize_t num_surrogates;
1361
1362 if (u == NULL)
1363 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001364
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001365 /* If the Unicode data is known at construction time, we can apply
1366 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 /* Optimization for empty strings */
1369 if (size == 0 && unicode_empty != NULL) {
1370 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001371 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001372 }
Tim Petersced69f82003-09-16 20:30:58 +00001373
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001374 /* Single character Unicode objects in the Latin-1 range are
1375 shared when using this constructor */
1376 if (size == 1 && *u < 256)
1377 return get_latin1_char((unsigned char)*u);
1378
1379 /* If not empty and not single character, copy the Unicode data
1380 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001381 if (find_maxchar_surrogates(u, u + size,
1382 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383 return NULL;
1384
1385 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1386 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001387 if (!unicode)
1388 return NULL;
1389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 switch (PyUnicode_KIND(unicode)) {
1391 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001392 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1394 break;
1395 case PyUnicode_2BYTE_KIND:
1396#if Py_UNICODE_SIZE == 2
1397 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1398#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001399 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1401#endif
1402 break;
1403 case PyUnicode_4BYTE_KIND:
1404#if SIZEOF_WCHAR_T == 2
1405 /* This is the only case which has to process surrogates, thus
1406 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001407 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408#else
1409 assert(num_surrogates == 0);
1410 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1411#endif
1412 break;
1413 default:
1414 assert(0 && "Impossible state");
1415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001416
1417 return (PyObject *)unicode;
1418}
1419
Alexander Belopolsky40018472011-02-26 01:02:56 +00001420PyObject *
1421PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001422{
1423 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001424
Benjamin Peterson14339b62009-01-31 16:36:08 +00001425 if (size < 0) {
1426 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001427 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001428 return NULL;
1429 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001430
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001431 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001432 some optimizations which share commonly used objects.
1433 Also, this means the input must be UTF-8, so fall back to the
1434 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001435 if (u != NULL) {
1436
Benjamin Peterson29060642009-01-31 22:14:21 +00001437 /* Optimization for empty strings */
1438 if (size == 0 && unicode_empty != NULL) {
1439 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001440 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001441 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001442
1443 /* Single characters are shared when using this constructor.
1444 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 if (size == 1 && Py_CHARMASK(*u) < 128)
1446 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001447
1448 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001449 }
1450
Walter Dörwald55507312007-05-18 13:12:10 +00001451 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001452 if (!unicode)
1453 return NULL;
1454
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001455 return (PyObject *)unicode;
1456}
1457
Alexander Belopolsky40018472011-02-26 01:02:56 +00001458PyObject *
1459PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001460{
1461 size_t size = strlen(u);
1462 if (size > PY_SSIZE_T_MAX) {
1463 PyErr_SetString(PyExc_OverflowError, "input too long");
1464 return NULL;
1465 }
1466
1467 return PyUnicode_FromStringAndSize(u, size);
1468}
1469
Victor Stinnere57b1c02011-09-28 22:20:48 +02001470static PyObject*
1471_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001472{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 PyObject *res;
1474 unsigned char max = 127;
1475 Py_ssize_t i;
1476 for (i = 0; i < size; i++) {
1477 if (u[i] & 0x80) {
1478 max = 255;
1479 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001480 }
1481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482 res = PyUnicode_New(size, max);
1483 if (!res)
1484 return NULL;
1485 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
1486 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001487}
1488
Victor Stinnere57b1c02011-09-28 22:20:48 +02001489static PyObject*
1490_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001491{
1492 PyObject *res;
1493 Py_UCS2 max = 0;
1494 Py_ssize_t i;
1495 for (i = 0; i < size; i++)
1496 if (u[i] > max)
1497 max = u[i];
1498 res = PyUnicode_New(size, max);
1499 if (!res)
1500 return NULL;
1501 if (max >= 256)
1502 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1503 else
1504 for (i = 0; i < size; i++)
1505 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
1506 return res;
1507}
1508
Victor Stinnere57b1c02011-09-28 22:20:48 +02001509static PyObject*
1510_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001511{
1512 PyObject *res;
1513 Py_UCS4 max = 0;
1514 Py_ssize_t i;
1515 for (i = 0; i < size; i++)
1516 if (u[i] > max)
1517 max = u[i];
1518 res = PyUnicode_New(size, max);
1519 if (!res)
1520 return NULL;
1521 if (max >= 0x10000)
1522 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
1523 else {
1524 int kind = PyUnicode_KIND(res);
1525 void *data = PyUnicode_DATA(res);
1526 for (i = 0; i < size; i++)
1527 PyUnicode_WRITE(kind, data, i, u[i]);
1528 }
1529 return res;
1530}
1531
1532PyObject*
1533PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1534{
1535 switch(kind) {
1536 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001537 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001538 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001539 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001541 return _PyUnicode_FromUCS4(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001542 }
Victor Stinner202b62b2011-10-01 23:48:37 +02001543 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001544 return NULL;
1545}
1546
Victor Stinner034f6cf2011-09-30 02:26:44 +02001547PyObject*
1548PyUnicode_Copy(PyObject *unicode)
1549{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001550 Py_ssize_t size;
1551 PyObject *copy;
1552 void *data;
1553
Victor Stinner034f6cf2011-09-30 02:26:44 +02001554 if (!PyUnicode_Check(unicode)) {
1555 PyErr_BadInternalCall();
1556 return NULL;
1557 }
1558 if (PyUnicode_READY(unicode))
1559 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001560
1561 size = PyUnicode_GET_LENGTH(unicode);
1562 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1563 if (!copy)
1564 return NULL;
1565 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1566
1567 data = PyUnicode_DATA(unicode);
1568 switch (PyUnicode_KIND(unicode))
1569 {
1570 case PyUnicode_1BYTE_KIND:
1571 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1572 break;
1573 case PyUnicode_2BYTE_KIND:
1574 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1575 break;
1576 case PyUnicode_4BYTE_KIND:
1577 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1578 break;
1579 default:
1580 assert(0);
1581 break;
1582 }
1583 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001584}
1585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001586
Victor Stinnerbc603d12011-10-02 01:00:40 +02001587/* Widen Unicode objects to larger buffers. Don't write terminating null
1588 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001589
1590void*
1591_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1592{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001593 Py_ssize_t len;
1594 void *result;
1595 unsigned int skind;
1596
1597 if (PyUnicode_READY(s))
1598 return NULL;
1599
1600 len = PyUnicode_GET_LENGTH(s);
1601 skind = PyUnicode_KIND(s);
1602 if (skind >= kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 PyErr_SetString(PyExc_RuntimeError, "invalid widening attempt");
1604 return NULL;
1605 }
1606 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001607 case PyUnicode_2BYTE_KIND:
1608 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1609 if (!result)
1610 return PyErr_NoMemory();
1611 assert(skind == PyUnicode_1BYTE_KIND);
1612 _PyUnicode_CONVERT_BYTES(
1613 Py_UCS1, Py_UCS2,
1614 PyUnicode_1BYTE_DATA(s),
1615 PyUnicode_1BYTE_DATA(s) + len,
1616 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001618 case PyUnicode_4BYTE_KIND:
1619 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1620 if (!result)
1621 return PyErr_NoMemory();
1622 if (skind == PyUnicode_2BYTE_KIND) {
1623 _PyUnicode_CONVERT_BYTES(
1624 Py_UCS2, Py_UCS4,
1625 PyUnicode_2BYTE_DATA(s),
1626 PyUnicode_2BYTE_DATA(s) + len,
1627 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001629 else {
1630 assert(skind == PyUnicode_1BYTE_KIND);
1631 _PyUnicode_CONVERT_BYTES(
1632 Py_UCS1, Py_UCS4,
1633 PyUnicode_1BYTE_DATA(s),
1634 PyUnicode_1BYTE_DATA(s) + len,
1635 result);
1636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001638 default:
1639 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001641 PyErr_SetString(PyExc_ValueError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 return NULL;
1643}
1644
1645static Py_UCS4*
1646as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1647 int copy_null)
1648{
1649 int kind;
1650 void *data;
1651 Py_ssize_t len, targetlen;
1652 if (PyUnicode_READY(string) == -1)
1653 return NULL;
1654 kind = PyUnicode_KIND(string);
1655 data = PyUnicode_DATA(string);
1656 len = PyUnicode_GET_LENGTH(string);
1657 targetlen = len;
1658 if (copy_null)
1659 targetlen++;
1660 if (!target) {
1661 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1662 PyErr_NoMemory();
1663 return NULL;
1664 }
1665 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1666 if (!target) {
1667 PyErr_NoMemory();
1668 return NULL;
1669 }
1670 }
1671 else {
1672 if (targetsize < targetlen) {
1673 PyErr_Format(PyExc_SystemError,
1674 "string is longer than the buffer");
1675 if (copy_null && 0 < targetsize)
1676 target[0] = 0;
1677 return NULL;
1678 }
1679 }
1680 if (kind != PyUnicode_4BYTE_KIND) {
1681 Py_ssize_t i;
1682 for (i = 0; i < len; i++)
1683 target[i] = PyUnicode_READ(kind, data, i);
1684 }
1685 else
1686 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
1687 if (copy_null)
1688 target[len] = 0;
1689 return target;
1690}
1691
1692Py_UCS4*
1693PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1694 int copy_null)
1695{
1696 if (target == NULL || targetsize < 1) {
1697 PyErr_BadInternalCall();
1698 return NULL;
1699 }
1700 return as_ucs4(string, target, targetsize, copy_null);
1701}
1702
1703Py_UCS4*
1704PyUnicode_AsUCS4Copy(PyObject *string)
1705{
1706 return as_ucs4(string, NULL, 0, 1);
1707}
1708
1709#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00001710
Alexander Belopolsky40018472011-02-26 01:02:56 +00001711PyObject *
1712PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001713{
Guido van Rossumd57fd912000-03-10 22:53:23 +00001714 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00001715 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001716 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00001717 PyErr_BadInternalCall();
1718 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001719 }
1720
Martin v. Löwis790465f2008-04-05 20:41:37 +00001721 if (size == -1) {
1722 size = wcslen(w);
1723 }
1724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001726}
1727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00001729
Walter Dörwald346737f2007-05-31 10:44:43 +00001730static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001731makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
1732 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00001733{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001734 *fmt++ = '%';
1735 if (width) {
1736 if (zeropad)
1737 *fmt++ = '0';
1738 fmt += sprintf(fmt, "%d", width);
1739 }
1740 if (precision)
1741 fmt += sprintf(fmt, ".%d", precision);
1742 if (longflag)
1743 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001744 else if (longlongflag) {
1745 /* longlongflag should only ever be nonzero on machines with
1746 HAVE_LONG_LONG defined */
1747#ifdef HAVE_LONG_LONG
1748 char *f = PY_FORMAT_LONG_LONG;
1749 while (*f)
1750 *fmt++ = *f++;
1751#else
1752 /* we shouldn't ever get here */
1753 assert(0);
1754 *fmt++ = 'l';
1755#endif
1756 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00001757 else if (size_tflag) {
1758 char *f = PY_FORMAT_SIZE_T;
1759 while (*f)
1760 *fmt++ = *f++;
1761 }
1762 *fmt++ = c;
1763 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00001764}
1765
Victor Stinner96865452011-03-01 23:44:09 +00001766/* helper for PyUnicode_FromFormatV() */
1767
1768static const char*
1769parse_format_flags(const char *f,
1770 int *p_width, int *p_precision,
1771 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
1772{
1773 int width, precision, longflag, longlongflag, size_tflag;
1774
1775 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
1776 f++;
1777 width = 0;
1778 while (Py_ISDIGIT((unsigned)*f))
1779 width = (width*10) + *f++ - '0';
1780 precision = 0;
1781 if (*f == '.') {
1782 f++;
1783 while (Py_ISDIGIT((unsigned)*f))
1784 precision = (precision*10) + *f++ - '0';
1785 if (*f == '%') {
1786 /* "%.3%s" => f points to "3" */
1787 f--;
1788 }
1789 }
1790 if (*f == '\0') {
1791 /* bogus format "%.1" => go backward, f points to "1" */
1792 f--;
1793 }
1794 if (p_width != NULL)
1795 *p_width = width;
1796 if (p_precision != NULL)
1797 *p_precision = precision;
1798
1799 /* Handle %ld, %lu, %lld and %llu. */
1800 longflag = 0;
1801 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00001802 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00001803
1804 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00001805 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00001806 longflag = 1;
1807 ++f;
1808 }
1809#ifdef HAVE_LONG_LONG
1810 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00001811 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001812 longlongflag = 1;
1813 f += 2;
1814 }
1815#endif
1816 }
1817 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00001818 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00001819 size_tflag = 1;
1820 ++f;
1821 }
1822 if (p_longflag != NULL)
1823 *p_longflag = longflag;
1824 if (p_longlongflag != NULL)
1825 *p_longlongflag = longlongflag;
1826 if (p_size_tflag != NULL)
1827 *p_size_tflag = size_tflag;
1828 return f;
1829}
1830
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001831/* maximum number of characters required for output of %ld. 21 characters
1832 allows for 64-bit integers (in decimal) and an optional sign. */
1833#define MAX_LONG_CHARS 21
1834/* maximum number of characters required for output of %lld.
1835 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
1836 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
1837#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
1838
Walter Dörwaldd2034312007-05-18 16:29:38 +00001839PyObject *
1840PyUnicode_FromFormatV(const char *format, va_list vargs)
1841{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001842 va_list count;
1843 Py_ssize_t callcount = 0;
1844 PyObject **callresults = NULL;
1845 PyObject **callresult = NULL;
1846 Py_ssize_t n = 0;
1847 int width = 0;
1848 int precision = 0;
1849 int zeropad;
1850 const char* f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851 PyUnicodeObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001852 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001853 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001854 Py_UCS4 maxchar = 127; /* result is ASCII by default */
1855 Py_UCS4 argmaxchar;
1856 Py_ssize_t numbersize = 0;
1857 char *numberresults = NULL;
1858 char *numberresult = NULL;
1859 Py_ssize_t i;
1860 int kind;
1861 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001862
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001863 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00001864 /* step 1: count the number of %S/%R/%A/%s format specifications
1865 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
1866 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 * result in an array)
1868 * also esimate a upper bound for all the number formats in the string,
1869 * numbers will be formated in step 3 and be keept in a '\0'-separated
1870 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00001871 for (f = format; *f; f++) {
1872 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00001873 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
1875 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
1876 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
1877 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00001878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00001880#ifdef HAVE_LONG_LONG
1881 if (longlongflag) {
1882 if (width < MAX_LONG_LONG_CHARS)
1883 width = MAX_LONG_LONG_CHARS;
1884 }
1885 else
1886#endif
1887 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
1888 including sign. Decimal takes the most space. This
1889 isn't enough for octal. If a width is specified we
1890 need more (which we allocate later). */
1891 if (width < MAX_LONG_CHARS)
1892 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001893
1894 /* account for the size + '\0' to separate numbers
1895 inside of the numberresults buffer */
1896 numbersize += (width + 1);
1897 }
1898 }
1899 else if ((unsigned char)*f > 127) {
1900 PyErr_Format(PyExc_ValueError,
1901 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
1902 "string, got a non-ASCII byte: 0x%02x",
1903 (unsigned char)*f);
1904 return NULL;
1905 }
1906 }
1907 /* step 2: allocate memory for the results of
1908 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
1909 if (callcount) {
1910 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
1911 if (!callresults) {
1912 PyErr_NoMemory();
1913 return NULL;
1914 }
1915 callresult = callresults;
1916 }
1917 /* step 2.5: allocate memory for the results of formating numbers */
1918 if (numbersize) {
1919 numberresults = PyObject_Malloc(numbersize);
1920 if (!numberresults) {
1921 PyErr_NoMemory();
1922 goto fail;
1923 }
1924 numberresult = numberresults;
1925 }
1926
1927 /* step 3: format numbers and figure out how large a buffer we need */
1928 for (f = format; *f; f++) {
1929 if (*f == '%') {
1930 const char* p;
1931 int longflag;
1932 int longlongflag;
1933 int size_tflag;
1934 int numprinted;
1935
1936 p = f;
1937 zeropad = (f[1] == '0');
1938 f = parse_format_flags(f, &width, &precision,
1939 &longflag, &longlongflag, &size_tflag);
1940 switch (*f) {
1941 case 'c':
1942 {
1943 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02001944 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001945 n++;
1946 break;
1947 }
1948 case '%':
1949 n++;
1950 break;
1951 case 'i':
1952 case 'd':
1953 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1954 width, precision, *f);
1955 if (longflag)
1956 numprinted = sprintf(numberresult, fmt,
1957 va_arg(count, long));
1958#ifdef HAVE_LONG_LONG
1959 else if (longlongflag)
1960 numprinted = sprintf(numberresult, fmt,
1961 va_arg(count, PY_LONG_LONG));
1962#endif
1963 else if (size_tflag)
1964 numprinted = sprintf(numberresult, fmt,
1965 va_arg(count, Py_ssize_t));
1966 else
1967 numprinted = sprintf(numberresult, fmt,
1968 va_arg(count, int));
1969 n += numprinted;
1970 /* advance by +1 to skip over the '\0' */
1971 numberresult += (numprinted + 1);
1972 assert(*(numberresult - 1) == '\0');
1973 assert(*(numberresult - 2) != '\0');
1974 assert(numprinted >= 0);
1975 assert(numberresult <= numberresults + numbersize);
1976 break;
1977 case 'u':
1978 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
1979 width, precision, 'u');
1980 if (longflag)
1981 numprinted = sprintf(numberresult, fmt,
1982 va_arg(count, unsigned long));
1983#ifdef HAVE_LONG_LONG
1984 else if (longlongflag)
1985 numprinted = sprintf(numberresult, fmt,
1986 va_arg(count, unsigned PY_LONG_LONG));
1987#endif
1988 else if (size_tflag)
1989 numprinted = sprintf(numberresult, fmt,
1990 va_arg(count, size_t));
1991 else
1992 numprinted = sprintf(numberresult, fmt,
1993 va_arg(count, unsigned int));
1994 n += numprinted;
1995 numberresult += (numprinted + 1);
1996 assert(*(numberresult - 1) == '\0');
1997 assert(*(numberresult - 2) != '\0');
1998 assert(numprinted >= 0);
1999 assert(numberresult <= numberresults + numbersize);
2000 break;
2001 case 'x':
2002 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2003 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2004 n += numprinted;
2005 numberresult += (numprinted + 1);
2006 assert(*(numberresult - 1) == '\0');
2007 assert(*(numberresult - 2) != '\0');
2008 assert(numprinted >= 0);
2009 assert(numberresult <= numberresults + numbersize);
2010 break;
2011 case 'p':
2012 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2013 /* %p is ill-defined: ensure leading 0x. */
2014 if (numberresult[1] == 'X')
2015 numberresult[1] = 'x';
2016 else if (numberresult[1] != 'x') {
2017 memmove(numberresult + 2, numberresult,
2018 strlen(numberresult) + 1);
2019 numberresult[0] = '0';
2020 numberresult[1] = 'x';
2021 numprinted += 2;
2022 }
2023 n += numprinted;
2024 numberresult += (numprinted + 1);
2025 assert(*(numberresult - 1) == '\0');
2026 assert(*(numberresult - 2) != '\0');
2027 assert(numprinted >= 0);
2028 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002029 break;
2030 case 's':
2031 {
2032 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002033 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002034 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2035 if (!str)
2036 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 /* since PyUnicode_DecodeUTF8 returns already flexible
2038 unicode objects, there is no need to call ready on them */
2039 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002040 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002042 /* Remember the str and switch to the next slot */
2043 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002044 break;
2045 }
2046 case 'U':
2047 {
2048 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002049 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 if (PyUnicode_READY(obj) == -1)
2051 goto fail;
2052 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002053 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002054 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002055 break;
2056 }
2057 case 'V':
2058 {
2059 PyObject *obj = va_arg(count, PyObject *);
2060 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002061 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002062 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002063 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002064 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002065 if (PyUnicode_READY(obj) == -1)
2066 goto fail;
2067 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002068 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002069 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002070 *callresult++ = NULL;
2071 }
2072 else {
2073 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2074 if (!str_obj)
2075 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002077 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002079 *callresult++ = str_obj;
2080 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002081 break;
2082 }
2083 case 'S':
2084 {
2085 PyObject *obj = va_arg(count, PyObject *);
2086 PyObject *str;
2087 assert(obj);
2088 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002089 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002090 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002092 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002093 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002094 /* Remember the str and switch to the next slot */
2095 *callresult++ = str;
2096 break;
2097 }
2098 case 'R':
2099 {
2100 PyObject *obj = va_arg(count, PyObject *);
2101 PyObject *repr;
2102 assert(obj);
2103 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002104 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002105 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002106 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002107 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002108 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002109 /* Remember the repr and switch to the next slot */
2110 *callresult++ = repr;
2111 break;
2112 }
2113 case 'A':
2114 {
2115 PyObject *obj = va_arg(count, PyObject *);
2116 PyObject *ascii;
2117 assert(obj);
2118 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002119 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002120 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002121 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002122 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002123 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002124 /* Remember the repr and switch to the next slot */
2125 *callresult++ = ascii;
2126 break;
2127 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002128 default:
2129 /* if we stumble upon an unknown
2130 formatting code, copy the rest of
2131 the format string to the output
2132 string. (we cannot just skip the
2133 code, since there's no way to know
2134 what's in the argument list) */
2135 n += strlen(p);
2136 goto expand;
2137 }
2138 } else
2139 n++;
2140 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002141 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002142 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002144 we don't have to resize the string.
2145 There can be no errors beyond this point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002146 string = (PyUnicodeObject *)PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002147 if (!string)
2148 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 kind = PyUnicode_KIND(string);
2150 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002151 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002152 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002153
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002154 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002155 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002156 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002157
2158 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002159 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2160 /* checking for == because the last argument could be a empty
2161 string, which causes i to point to end, the assert at the end of
2162 the loop */
2163 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002164
Benjamin Peterson14339b62009-01-31 16:36:08 +00002165 switch (*f) {
2166 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002167 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002168 const int ordinal = va_arg(vargs, int);
2169 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002170 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002171 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002172 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002173 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002174 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002175 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 case 'p':
2177 /* unused, since we already have the result */
2178 if (*f == 'p')
2179 (void) va_arg(vargs, void *);
2180 else
2181 (void) va_arg(vargs, int);
2182 /* extract the result from numberresults and append. */
2183 for (; *numberresult; ++i, ++numberresult)
2184 PyUnicode_WRITE(kind, data, i, *numberresult);
2185 /* skip over the separating '\0' */
2186 assert(*numberresult == '\0');
2187 numberresult++;
2188 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002189 break;
2190 case 's':
2191 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002192 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002194 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002195 size = PyUnicode_GET_LENGTH(*callresult);
2196 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002197 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2198 *callresult, 0,
2199 size) < 0)
2200 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002202 /* We're done with the unicode()/repr() => forget it */
2203 Py_DECREF(*callresult);
2204 /* switch to next unicode()/repr() result */
2205 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002206 break;
2207 }
2208 case 'U':
2209 {
2210 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002211 Py_ssize_t size;
2212 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2213 size = PyUnicode_GET_LENGTH(obj);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002214 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2215 obj, 0,
2216 size) < 0)
2217 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002219 break;
2220 }
2221 case 'V':
2222 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002224 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002225 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002226 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 size = PyUnicode_GET_LENGTH(obj);
2228 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002229 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2230 obj, 0,
2231 size) < 0)
2232 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002233 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002234 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235 size = PyUnicode_GET_LENGTH(*callresult);
2236 assert(PyUnicode_KIND(*callresult) <=
2237 PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002238 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2239 *callresult,
2240 0, size) < 0)
2241 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002243 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002244 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002245 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002246 break;
2247 }
2248 case 'S':
2249 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002250 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002251 {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002252 /* unused, since we already have the result */
2253 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002254 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02002255 if (PyUnicode_CopyCharacters((PyObject*)string, i,
2256 *callresult, 0,
2257 PyUnicode_GET_LENGTH(*callresult)) < 0)
2258 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259 i += PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002260 /* We're done with the unicode()/repr() => forget it */
2261 Py_DECREF(*callresult);
2262 /* switch to next unicode()/repr() result */
2263 ++callresult;
2264 break;
2265 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002266 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002268 break;
2269 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 for (; *p; ++p, ++i)
2271 PyUnicode_WRITE(kind, data, i, *p);
2272 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002273 goto end;
2274 }
Victor Stinner1205f272010-09-11 00:54:47 +00002275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 else {
2277 assert(i < PyUnicode_GET_LENGTH(string));
2278 PyUnicode_WRITE(kind, data, i++, *f);
2279 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002282
Benjamin Peterson29060642009-01-31 22:14:21 +00002283 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002284 if (callresults)
2285 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 if (numberresults)
2287 PyObject_Free(numberresults);
2288 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002289 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002290 if (callresults) {
2291 PyObject **callresult2 = callresults;
2292 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002293 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002294 ++callresult2;
2295 }
2296 PyObject_Free(callresults);
2297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002298 if (numberresults)
2299 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002300 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002301}
2302
Walter Dörwaldd2034312007-05-18 16:29:38 +00002303PyObject *
2304PyUnicode_FromFormat(const char *format, ...)
2305{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002306 PyObject* ret;
2307 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002308
2309#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002310 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002311#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002312 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002313#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002314 ret = PyUnicode_FromFormatV(format, vargs);
2315 va_end(vargs);
2316 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002317}
2318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002319#ifdef HAVE_WCHAR_H
2320
Victor Stinner5593d8a2010-10-02 11:11:27 +00002321/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2322 convert a Unicode object to a wide character string.
2323
Victor Stinnerd88d9832011-09-06 02:00:05 +02002324 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002325 character) required to convert the unicode object. Ignore size argument.
2326
Victor Stinnerd88d9832011-09-06 02:00:05 +02002327 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002328 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002329 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002330static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002331unicode_aswidechar(PyUnicodeObject *unicode,
2332 wchar_t *w,
2333 Py_ssize_t size)
2334{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002335 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002336 const wchar_t *wstr;
2337
2338 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2339 if (wstr == NULL)
2340 return -1;
2341
Victor Stinner5593d8a2010-10-02 11:11:27 +00002342 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002343 if (size > res)
2344 size = res + 1;
2345 else
2346 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002347 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002348 return res;
2349 }
2350 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002352}
2353
2354Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002355PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002356 wchar_t *w,
2357 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002358{
2359 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002360 PyErr_BadInternalCall();
2361 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002362 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002363 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002364}
2365
Victor Stinner137c34c2010-09-29 10:25:54 +00002366wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002367PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002368 Py_ssize_t *size)
2369{
2370 wchar_t* buffer;
2371 Py_ssize_t buflen;
2372
2373 if (unicode == NULL) {
2374 PyErr_BadInternalCall();
2375 return NULL;
2376 }
2377
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002378 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 if (buflen == -1)
2380 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002381 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002382 PyErr_NoMemory();
2383 return NULL;
2384 }
2385
Victor Stinner137c34c2010-09-29 10:25:54 +00002386 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2387 if (buffer == NULL) {
2388 PyErr_NoMemory();
2389 return NULL;
2390 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002391 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002392 if (buflen == -1)
2393 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002394 if (size != NULL)
2395 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002396 return buffer;
2397}
2398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002400
Alexander Belopolsky40018472011-02-26 01:02:56 +00002401PyObject *
2402PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002403{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002405 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002406 PyErr_SetString(PyExc_ValueError,
2407 "chr() arg not in range(0x110000)");
2408 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002409 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 if (ordinal < 256)
2412 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 v = PyUnicode_New(1, ordinal);
2415 if (v == NULL)
2416 return NULL;
2417 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
2418 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002419}
2420
Alexander Belopolsky40018472011-02-26 01:02:56 +00002421PyObject *
2422PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002423{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002424 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002425 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002426 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002427 if (PyUnicode_READY(obj))
2428 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002429 Py_INCREF(obj);
2430 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002431 }
2432 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002433 /* For a Unicode subtype that's not a Unicode object,
2434 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002435 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002436 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002437 PyErr_Format(PyExc_TypeError,
2438 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002439 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002440 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002441}
2442
Alexander Belopolsky40018472011-02-26 01:02:56 +00002443PyObject *
2444PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002445 const char *encoding,
2446 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002447{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002448 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002449 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002450
Guido van Rossumd57fd912000-03-10 22:53:23 +00002451 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002452 PyErr_BadInternalCall();
2453 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002454 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002455
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002456 /* Decoding bytes objects is the most common case and should be fast */
2457 if (PyBytes_Check(obj)) {
2458 if (PyBytes_GET_SIZE(obj) == 0) {
2459 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002460 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002461 }
2462 else {
2463 v = PyUnicode_Decode(
2464 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2465 encoding, errors);
2466 }
2467 return v;
2468 }
2469
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002470 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002471 PyErr_SetString(PyExc_TypeError,
2472 "decoding str is not supported");
2473 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002474 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002475
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002476 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2477 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2478 PyErr_Format(PyExc_TypeError,
2479 "coercing to str: need bytes, bytearray "
2480 "or buffer-like object, %.80s found",
2481 Py_TYPE(obj)->tp_name);
2482 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002483 }
Tim Petersced69f82003-09-16 20:30:58 +00002484
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002485 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002486 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002487 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002488 }
Tim Petersced69f82003-09-16 20:30:58 +00002489 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002490 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002491
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002492 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002493 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002494}
2495
Victor Stinner600d3be2010-06-10 12:00:55 +00002496/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002497 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2498 1 on success. */
2499static int
2500normalize_encoding(const char *encoding,
2501 char *lower,
2502 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002503{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002504 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002505 char *l;
2506 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002507
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002508 e = encoding;
2509 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002510 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002511 while (*e) {
2512 if (l == l_end)
2513 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002514 if (Py_ISUPPER(*e)) {
2515 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002516 }
2517 else if (*e == '_') {
2518 *l++ = '-';
2519 e++;
2520 }
2521 else {
2522 *l++ = *e++;
2523 }
2524 }
2525 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002526 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002527}
2528
Alexander Belopolsky40018472011-02-26 01:02:56 +00002529PyObject *
2530PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002531 Py_ssize_t size,
2532 const char *encoding,
2533 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002534{
2535 PyObject *buffer = NULL, *unicode;
2536 Py_buffer info;
2537 char lower[11]; /* Enough for any encoding shortcut */
2538
2539 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002540 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002541
2542 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002543 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002544 if ((strcmp(lower, "utf-8") == 0) ||
2545 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002546 return PyUnicode_DecodeUTF8(s, size, errors);
2547 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002548 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002549 (strcmp(lower, "iso-8859-1") == 0))
2550 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002551#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002552 else if (strcmp(lower, "mbcs") == 0)
2553 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002554#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002555 else if (strcmp(lower, "ascii") == 0)
2556 return PyUnicode_DecodeASCII(s, size, errors);
2557 else if (strcmp(lower, "utf-16") == 0)
2558 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2559 else if (strcmp(lower, "utf-32") == 0)
2560 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2561 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002562
2563 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002564 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002565 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002566 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002567 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002568 if (buffer == NULL)
2569 goto onError;
2570 unicode = PyCodec_Decode(buffer, encoding, errors);
2571 if (unicode == NULL)
2572 goto onError;
2573 if (!PyUnicode_Check(unicode)) {
2574 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002575 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002576 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002577 Py_DECREF(unicode);
2578 goto onError;
2579 }
2580 Py_DECREF(buffer);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002581 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 Py_DECREF(unicode);
2583 return NULL;
2584 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002585 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002586
Benjamin Peterson29060642009-01-31 22:14:21 +00002587 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002588 Py_XDECREF(buffer);
2589 return NULL;
2590}
2591
Alexander Belopolsky40018472011-02-26 01:02:56 +00002592PyObject *
2593PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002594 const char *encoding,
2595 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002596{
2597 PyObject *v;
2598
2599 if (!PyUnicode_Check(unicode)) {
2600 PyErr_BadArgument();
2601 goto onError;
2602 }
2603
2604 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002605 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002606
2607 /* Decode via the codec registry */
2608 v = PyCodec_Decode(unicode, encoding, errors);
2609 if (v == NULL)
2610 goto onError;
2611 return v;
2612
Benjamin Peterson29060642009-01-31 22:14:21 +00002613 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002614 return NULL;
2615}
2616
Alexander Belopolsky40018472011-02-26 01:02:56 +00002617PyObject *
2618PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002619 const char *encoding,
2620 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002621{
2622 PyObject *v;
2623
2624 if (!PyUnicode_Check(unicode)) {
2625 PyErr_BadArgument();
2626 goto onError;
2627 }
2628
2629 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002630 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002631
2632 /* Decode via the codec registry */
2633 v = PyCodec_Decode(unicode, encoding, errors);
2634 if (v == NULL)
2635 goto onError;
2636 if (!PyUnicode_Check(v)) {
2637 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002638 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002639 Py_TYPE(v)->tp_name);
2640 Py_DECREF(v);
2641 goto onError;
2642 }
2643 return v;
2644
Benjamin Peterson29060642009-01-31 22:14:21 +00002645 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002646 return NULL;
2647}
2648
Alexander Belopolsky40018472011-02-26 01:02:56 +00002649PyObject *
2650PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002651 Py_ssize_t size,
2652 const char *encoding,
2653 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002654{
2655 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002656
Guido van Rossumd57fd912000-03-10 22:53:23 +00002657 unicode = PyUnicode_FromUnicode(s, size);
2658 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002659 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002660 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2661 Py_DECREF(unicode);
2662 return v;
2663}
2664
Alexander Belopolsky40018472011-02-26 01:02:56 +00002665PyObject *
2666PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002667 const char *encoding,
2668 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002669{
2670 PyObject *v;
2671
2672 if (!PyUnicode_Check(unicode)) {
2673 PyErr_BadArgument();
2674 goto onError;
2675 }
2676
2677 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002678 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002679
2680 /* Encode via the codec registry */
2681 v = PyCodec_Encode(unicode, encoding, errors);
2682 if (v == NULL)
2683 goto onError;
2684 return v;
2685
Benjamin Peterson29060642009-01-31 22:14:21 +00002686 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002687 return NULL;
2688}
2689
Victor Stinnerad158722010-10-27 00:25:46 +00002690PyObject *
2691PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002692{
Victor Stinner99b95382011-07-04 14:23:54 +02002693#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002694 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2695 PyUnicode_GET_SIZE(unicode),
2696 NULL);
2697#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002698 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00002699#else
Victor Stinner793b5312011-04-27 00:24:21 +02002700 PyInterpreterState *interp = PyThreadState_GET()->interp;
2701 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2702 cannot use it to encode and decode filenames before it is loaded. Load
2703 the Python codec requires to encode at least its own filename. Use the C
2704 version of the locale codec until the codec registry is initialized and
2705 the Python codec is loaded.
2706
2707 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2708 cannot only rely on it: check also interp->fscodec_initialized for
2709 subinterpreters. */
2710 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00002711 return PyUnicode_AsEncodedString(unicode,
2712 Py_FileSystemDefaultEncoding,
2713 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00002714 }
2715 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002716 /* locale encoding with surrogateescape */
2717 wchar_t *wchar;
2718 char *bytes;
2719 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00002720 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002721
2722 wchar = PyUnicode_AsWideCharString(unicode, NULL);
2723 if (wchar == NULL)
2724 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002725 bytes = _Py_wchar2char(wchar, &error_pos);
2726 if (bytes == NULL) {
2727 if (error_pos != (size_t)-1) {
2728 char *errmsg = strerror(errno);
2729 PyObject *exc = NULL;
2730 if (errmsg == NULL)
2731 errmsg = "Py_wchar2char() failed";
2732 raise_encode_exception(&exc,
2733 "filesystemencoding",
2734 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
2735 error_pos, error_pos+1,
2736 errmsg);
2737 Py_XDECREF(exc);
2738 }
2739 else
2740 PyErr_NoMemory();
2741 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002742 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00002743 }
2744 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002745
2746 bytes_obj = PyBytes_FromString(bytes);
2747 PyMem_Free(bytes);
2748 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00002749 }
Victor Stinnerad158722010-10-27 00:25:46 +00002750#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00002751}
2752
Alexander Belopolsky40018472011-02-26 01:02:56 +00002753PyObject *
2754PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002755 const char *encoding,
2756 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757{
2758 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00002759 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00002760
Guido van Rossumd57fd912000-03-10 22:53:23 +00002761 if (!PyUnicode_Check(unicode)) {
2762 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002763 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002764 }
Fred Drakee4315f52000-05-09 19:53:39 +00002765
Victor Stinner2f283c22011-03-02 01:21:46 +00002766 if (encoding == NULL) {
2767 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002769 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00002771 }
Fred Drakee4315f52000-05-09 19:53:39 +00002772
2773 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002774 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002775 if ((strcmp(lower, "utf-8") == 0) ||
2776 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00002777 {
Victor Stinner2f283c22011-03-02 01:21:46 +00002778 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002779 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00002780 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002781 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00002782 }
Victor Stinner37296e82010-06-10 13:36:23 +00002783 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002784 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002785 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002787#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002788 else if (strcmp(lower, "mbcs") == 0)
2789 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2790 PyUnicode_GET_SIZE(unicode),
2791 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002792#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002793 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002794 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00002795 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002796
2797 /* Encode via the codec registry */
2798 v = PyCodec_Encode(unicode, encoding, errors);
2799 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002800 return NULL;
2801
2802 /* The normal path */
2803 if (PyBytes_Check(v))
2804 return v;
2805
2806 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002807 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002808 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002809 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002810
2811 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
2812 "encoder %s returned bytearray instead of bytes",
2813 encoding);
2814 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002815 Py_DECREF(v);
2816 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002817 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002818
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00002819 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
2820 Py_DECREF(v);
2821 return b;
2822 }
2823
2824 PyErr_Format(PyExc_TypeError,
2825 "encoder did not return a bytes object (type=%.400s)",
2826 Py_TYPE(v)->tp_name);
2827 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002828 return NULL;
2829}
2830
Alexander Belopolsky40018472011-02-26 01:02:56 +00002831PyObject *
2832PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002833 const char *encoding,
2834 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002835{
2836 PyObject *v;
2837
2838 if (!PyUnicode_Check(unicode)) {
2839 PyErr_BadArgument();
2840 goto onError;
2841 }
2842
2843 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002844 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002845
2846 /* Encode via the codec registry */
2847 v = PyCodec_Encode(unicode, encoding, errors);
2848 if (v == NULL)
2849 goto onError;
2850 if (!PyUnicode_Check(v)) {
2851 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002852 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002853 Py_TYPE(v)->tp_name);
2854 Py_DECREF(v);
2855 goto onError;
2856 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002857 return v;
Tim Petersced69f82003-09-16 20:30:58 +00002858
Benjamin Peterson29060642009-01-31 22:14:21 +00002859 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002860 return NULL;
2861}
2862
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002863PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00002864PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002865 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00002866 return PyUnicode_DecodeFSDefaultAndSize(s, size);
2867}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002868
Christian Heimes5894ba72007-11-04 11:43:14 +00002869PyObject*
2870PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
2871{
Victor Stinner99b95382011-07-04 14:23:54 +02002872#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002873 return PyUnicode_DecodeMBCS(s, size, NULL);
2874#elif defined(__APPLE__)
2875 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
2876#else
Victor Stinner793b5312011-04-27 00:24:21 +02002877 PyInterpreterState *interp = PyThreadState_GET()->interp;
2878 /* Bootstrap check: if the filesystem codec is implemented in Python, we
2879 cannot use it to encode and decode filenames before it is loaded. Load
2880 the Python codec requires to encode at least its own filename. Use the C
2881 version of the locale codec until the codec registry is initialized and
2882 the Python codec is loaded.
2883
2884 Py_FileSystemDefaultEncoding is shared between all interpreters, we
2885 cannot only rely on it: check also interp->fscodec_initialized for
2886 subinterpreters. */
2887 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002888 return PyUnicode_Decode(s, size,
2889 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00002890 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002891 }
2892 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002893 /* locale encoding with surrogateescape */
2894 wchar_t *wchar;
2895 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00002896 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002897
2898 if (s[size] != '\0' || size != strlen(s)) {
2899 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2900 return NULL;
2901 }
2902
Victor Stinner168e1172010-10-16 23:16:16 +00002903 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002904 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00002905 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002906
Victor Stinner168e1172010-10-16 23:16:16 +00002907 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00002908 PyMem_Free(wchar);
2909 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002910 }
Victor Stinnerad158722010-10-27 00:25:46 +00002911#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00002912}
2913
Martin v. Löwis011e8422009-05-05 04:43:17 +00002914
2915int
2916PyUnicode_FSConverter(PyObject* arg, void* addr)
2917{
2918 PyObject *output = NULL;
2919 Py_ssize_t size;
2920 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002921 if (arg == NULL) {
2922 Py_DECREF(*(PyObject**)addr);
2923 return 1;
2924 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00002925 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00002926 output = arg;
2927 Py_INCREF(output);
2928 }
2929 else {
2930 arg = PyUnicode_FromObject(arg);
2931 if (!arg)
2932 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002933 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002934 Py_DECREF(arg);
2935 if (!output)
2936 return 0;
2937 if (!PyBytes_Check(output)) {
2938 Py_DECREF(output);
2939 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
2940 return 0;
2941 }
2942 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00002943 size = PyBytes_GET_SIZE(output);
2944 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00002945 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05002946 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00002947 Py_DECREF(output);
2948 return 0;
2949 }
2950 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00002951 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00002952}
2953
2954
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002955int
2956PyUnicode_FSDecoder(PyObject* arg, void* addr)
2957{
2958 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002959 if (arg == NULL) {
2960 Py_DECREF(*(PyObject**)addr);
2961 return 1;
2962 }
2963 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002964 if (PyUnicode_READY(arg))
2965 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002966 output = arg;
2967 Py_INCREF(output);
2968 }
2969 else {
2970 arg = PyBytes_FromObject(arg);
2971 if (!arg)
2972 return 0;
2973 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
2974 PyBytes_GET_SIZE(arg));
2975 Py_DECREF(arg);
2976 if (!output)
2977 return 0;
2978 if (!PyUnicode_Check(output)) {
2979 Py_DECREF(output);
2980 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
2981 return 0;
2982 }
2983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002984 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
2985 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00002986 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
2987 Py_DECREF(output);
2988 return 0;
2989 }
2990 *(PyObject**)addr = output;
2991 return Py_CLEANUP_SUPPORTED;
2992}
2993
2994
Martin v. Löwis5b222132007-06-10 09:51:05 +00002995char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002996PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002997{
Christian Heimesf3863112007-11-22 07:46:41 +00002998 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002999 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3000
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003001 if (!PyUnicode_Check(unicode)) {
3002 PyErr_BadArgument();
3003 return NULL;
3004 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003005 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003006 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003008 if (PyUnicode_UTF8(unicode) == NULL) {
3009 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003010 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3011 if (bytes == NULL)
3012 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003013 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3014 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003015 Py_DECREF(bytes);
3016 return NULL;
3017 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003018 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3019 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003020 Py_DECREF(bytes);
3021 }
3022
3023 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003024 *psize = PyUnicode_UTF8_LENGTH(unicode);
3025 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003026}
3027
3028char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003029PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003030{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003031 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3032}
3033
3034#ifdef Py_DEBUG
3035int unicode_as_unicode_calls = 0;
3036#endif
3037
3038
3039Py_UNICODE *
3040PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3041{
3042 PyUnicodeObject *u;
3043 const unsigned char *one_byte;
3044#if SIZEOF_WCHAR_T == 4
3045 const Py_UCS2 *two_bytes;
3046#else
3047 const Py_UCS4 *four_bytes;
3048 const Py_UCS4 *ucs4_end;
3049 Py_ssize_t num_surrogates;
3050#endif
3051 wchar_t *w;
3052 wchar_t *wchar_end;
3053
3054 if (!PyUnicode_Check(unicode)) {
3055 PyErr_BadArgument();
3056 return NULL;
3057 }
3058 u = (PyUnicodeObject*)unicode;
3059 if (_PyUnicode_WSTR(u) == NULL) {
3060 /* Non-ASCII compact unicode object */
3061 assert(_PyUnicode_KIND(u) != 0);
3062 assert(PyUnicode_IS_READY(u));
3063
3064#ifdef Py_DEBUG
3065 ++unicode_as_unicode_calls;
3066#endif
3067
3068 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3069#if SIZEOF_WCHAR_T == 2
3070 four_bytes = PyUnicode_4BYTE_DATA(u);
3071 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3072 num_surrogates = 0;
3073
3074 for (; four_bytes < ucs4_end; ++four_bytes) {
3075 if (*four_bytes > 0xFFFF)
3076 ++num_surrogates;
3077 }
3078
3079 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3080 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3081 if (!_PyUnicode_WSTR(u)) {
3082 PyErr_NoMemory();
3083 return NULL;
3084 }
3085 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3086
3087 w = _PyUnicode_WSTR(u);
3088 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3089 four_bytes = PyUnicode_4BYTE_DATA(u);
3090 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3091 if (*four_bytes > 0xFFFF) {
3092 /* encode surrogate pair in this case */
3093 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3094 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3095 }
3096 else
3097 *w = *four_bytes;
3098
3099 if (w > wchar_end) {
3100 assert(0 && "Miscalculated string end");
3101 }
3102 }
3103 *w = 0;
3104#else
3105 /* sizeof(wchar_t) == 4 */
3106 Py_FatalError("Impossible unicode object state, wstr and str "
3107 "should share memory already.");
3108 return NULL;
3109#endif
3110 }
3111 else {
3112 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3113 (_PyUnicode_LENGTH(u) + 1));
3114 if (!_PyUnicode_WSTR(u)) {
3115 PyErr_NoMemory();
3116 return NULL;
3117 }
3118 if (!PyUnicode_IS_COMPACT_ASCII(u))
3119 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3120 w = _PyUnicode_WSTR(u);
3121 wchar_end = w + _PyUnicode_LENGTH(u);
3122
3123 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3124 one_byte = PyUnicode_1BYTE_DATA(u);
3125 for (; w < wchar_end; ++one_byte, ++w)
3126 *w = *one_byte;
3127 /* null-terminate the wstr */
3128 *w = 0;
3129 }
3130 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3131#if SIZEOF_WCHAR_T == 4
3132 two_bytes = PyUnicode_2BYTE_DATA(u);
3133 for (; w < wchar_end; ++two_bytes, ++w)
3134 *w = *two_bytes;
3135 /* null-terminate the wstr */
3136 *w = 0;
3137#else
3138 /* sizeof(wchar_t) == 2 */
3139 PyObject_FREE(_PyUnicode_WSTR(u));
3140 _PyUnicode_WSTR(u) = NULL;
3141 Py_FatalError("Impossible unicode object state, wstr "
3142 "and str should share memory already.");
3143 return NULL;
3144#endif
3145 }
3146 else {
3147 assert(0 && "This should never happen.");
3148 }
3149 }
3150 }
3151 if (size != NULL)
3152 *size = PyUnicode_WSTR_LENGTH(u);
3153 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003154}
3155
Alexander Belopolsky40018472011-02-26 01:02:56 +00003156Py_UNICODE *
3157PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003159 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003160}
3161
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003162
Alexander Belopolsky40018472011-02-26 01:02:56 +00003163Py_ssize_t
3164PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003165{
3166 if (!PyUnicode_Check(unicode)) {
3167 PyErr_BadArgument();
3168 goto onError;
3169 }
3170 return PyUnicode_GET_SIZE(unicode);
3171
Benjamin Peterson29060642009-01-31 22:14:21 +00003172 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003173 return -1;
3174}
3175
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003176Py_ssize_t
3177PyUnicode_GetLength(PyObject *unicode)
3178{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003179 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003180 PyErr_BadArgument();
3181 return -1;
3182 }
3183
3184 return PyUnicode_GET_LENGTH(unicode);
3185}
3186
3187Py_UCS4
3188PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3189{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003190 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3191 PyErr_BadArgument();
3192 return (Py_UCS4)-1;
3193 }
3194 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3195 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003196 return (Py_UCS4)-1;
3197 }
3198 return PyUnicode_READ_CHAR(unicode, index);
3199}
3200
3201int
3202PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3203{
3204 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003205 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003206 return -1;
3207 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003208 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3209 PyErr_SetString(PyExc_IndexError, "string index out of range");
3210 return -1;
3211 }
3212 if (_PyUnicode_Dirty(unicode))
3213 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003214 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3215 index, ch);
3216 return 0;
3217}
3218
Alexander Belopolsky40018472011-02-26 01:02:56 +00003219const char *
3220PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003221{
Victor Stinner42cb4622010-09-01 19:39:01 +00003222 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003223}
3224
Victor Stinner554f3f02010-06-16 23:33:54 +00003225/* create or adjust a UnicodeDecodeError */
3226static void
3227make_decode_exception(PyObject **exceptionObject,
3228 const char *encoding,
3229 const char *input, Py_ssize_t length,
3230 Py_ssize_t startpos, Py_ssize_t endpos,
3231 const char *reason)
3232{
3233 if (*exceptionObject == NULL) {
3234 *exceptionObject = PyUnicodeDecodeError_Create(
3235 encoding, input, length, startpos, endpos, reason);
3236 }
3237 else {
3238 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3239 goto onError;
3240 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3241 goto onError;
3242 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3243 goto onError;
3244 }
3245 return;
3246
3247onError:
3248 Py_DECREF(*exceptionObject);
3249 *exceptionObject = NULL;
3250}
3251
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003252/* error handling callback helper:
3253 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003254 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003255 and adjust various state variables.
3256 return 0 on success, -1 on error
3257*/
3258
Alexander Belopolsky40018472011-02-26 01:02:56 +00003259static int
3260unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003261 const char *encoding, const char *reason,
3262 const char **input, const char **inend, Py_ssize_t *startinpos,
3263 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3264 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003265{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003266 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003267
3268 PyObject *restuple = NULL;
3269 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003270 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003271 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003272 Py_ssize_t requiredsize;
3273 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003274 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003275 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003276 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003277 int res = -1;
3278
3279 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003280 *errorHandler = PyCodec_LookupError(errors);
3281 if (*errorHandler == NULL)
3282 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003283 }
3284
Victor Stinner554f3f02010-06-16 23:33:54 +00003285 make_decode_exception(exceptionObject,
3286 encoding,
3287 *input, *inend - *input,
3288 *startinpos, *endinpos,
3289 reason);
3290 if (*exceptionObject == NULL)
3291 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003292
3293 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3294 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003295 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003296 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003297 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003298 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003299 }
3300 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003301 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003302
3303 /* Copy back the bytes variables, which might have been modified by the
3304 callback */
3305 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3306 if (!inputobj)
3307 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003308 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003309 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003310 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003311 *input = PyBytes_AS_STRING(inputobj);
3312 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003313 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003314 /* we can DECREF safely, as the exception has another reference,
3315 so the object won't go away. */
3316 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003317
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003318 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003319 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003320 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003321 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3322 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003323 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003324
3325 /* need more space? (at least enough for what we
3326 have+the replacement+the rest of the string (starting
3327 at the new input position), so we won't have to check space
3328 when there are no errors in the rest of the string) */
3329 repptr = PyUnicode_AS_UNICODE(repunicode);
3330 repsize = PyUnicode_GET_SIZE(repunicode);
3331 requiredsize = *outpos + repsize + insize-newpos;
3332 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003333 if (requiredsize<2*outsize)
3334 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003335 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003336 goto onError;
3337 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003338 }
3339 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003340 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003341 Py_UNICODE_COPY(*outptr, repptr, repsize);
3342 *outptr += repsize;
3343 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003344
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003345 /* we made it! */
3346 res = 0;
3347
Benjamin Peterson29060642009-01-31 22:14:21 +00003348 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003349 Py_XDECREF(restuple);
3350 return res;
3351}
3352
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003353/* --- UTF-7 Codec -------------------------------------------------------- */
3354
Antoine Pitrou244651a2009-05-04 18:56:13 +00003355/* See RFC2152 for details. We encode conservatively and decode liberally. */
3356
3357/* Three simple macros defining base-64. */
3358
3359/* Is c a base-64 character? */
3360
3361#define IS_BASE64(c) \
3362 (((c) >= 'A' && (c) <= 'Z') || \
3363 ((c) >= 'a' && (c) <= 'z') || \
3364 ((c) >= '0' && (c) <= '9') || \
3365 (c) == '+' || (c) == '/')
3366
3367/* given that c is a base-64 character, what is its base-64 value? */
3368
3369#define FROM_BASE64(c) \
3370 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3371 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3372 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3373 (c) == '+' ? 62 : 63)
3374
3375/* What is the base-64 character of the bottom 6 bits of n? */
3376
3377#define TO_BASE64(n) \
3378 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3379
3380/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3381 * decoded as itself. We are permissive on decoding; the only ASCII
3382 * byte not decoding to itself is the + which begins a base64
3383 * string. */
3384
3385#define DECODE_DIRECT(c) \
3386 ((c) <= 127 && (c) != '+')
3387
3388/* The UTF-7 encoder treats ASCII characters differently according to
3389 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3390 * the above). See RFC2152. This array identifies these different
3391 * sets:
3392 * 0 : "Set D"
3393 * alphanumeric and '(),-./:?
3394 * 1 : "Set O"
3395 * !"#$%&*;<=>@[]^_`{|}
3396 * 2 : "whitespace"
3397 * ht nl cr sp
3398 * 3 : special (must be base64 encoded)
3399 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3400 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003401
Tim Petersced69f82003-09-16 20:30:58 +00003402static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003403char utf7_category[128] = {
3404/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3405 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3406/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3407 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3408/* sp ! " # $ % & ' ( ) * + , - . / */
3409 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3410/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3411 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3412/* @ A B C D E F G H I J K L M N O */
3413 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3414/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3415 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3416/* ` a b c d e f g h i j k l m n o */
3417 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3418/* p q r s t u v w x y z { | } ~ del */
3419 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003420};
3421
Antoine Pitrou244651a2009-05-04 18:56:13 +00003422/* ENCODE_DIRECT: this character should be encoded as itself. The
3423 * answer depends on whether we are encoding set O as itself, and also
3424 * on whether we are encoding whitespace as itself. RFC2152 makes it
3425 * clear that the answers to these questions vary between
3426 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003427
Antoine Pitrou244651a2009-05-04 18:56:13 +00003428#define ENCODE_DIRECT(c, directO, directWS) \
3429 ((c) < 128 && (c) > 0 && \
3430 ((utf7_category[(c)] == 0) || \
3431 (directWS && (utf7_category[(c)] == 2)) || \
3432 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003433
Alexander Belopolsky40018472011-02-26 01:02:56 +00003434PyObject *
3435PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003436 Py_ssize_t size,
3437 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003438{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003439 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3440}
3441
Antoine Pitrou244651a2009-05-04 18:56:13 +00003442/* The decoder. The only state we preserve is our read position,
3443 * i.e. how many characters we have consumed. So if we end in the
3444 * middle of a shift sequence we have to back off the read position
3445 * and the output to the beginning of the sequence, otherwise we lose
3446 * all the shift state (seen bits, number of bits seen, high
3447 * surrogate). */
3448
Alexander Belopolsky40018472011-02-26 01:02:56 +00003449PyObject *
3450PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003451 Py_ssize_t size,
3452 const char *errors,
3453 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003454{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003455 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003456 Py_ssize_t startinpos;
3457 Py_ssize_t endinpos;
3458 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003459 const char *e;
3460 PyUnicodeObject *unicode;
3461 Py_UNICODE *p;
3462 const char *errmsg = "";
3463 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003464 Py_UNICODE *shiftOutStart;
3465 unsigned int base64bits = 0;
3466 unsigned long base64buffer = 0;
3467 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003468 PyObject *errorHandler = NULL;
3469 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003470
3471 unicode = _PyUnicode_New(size);
3472 if (!unicode)
3473 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003474 if (size == 0) {
3475 if (consumed)
3476 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003477 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003478 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003481 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003482 e = s + size;
3483
3484 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003485 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003486 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003487 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003488
Antoine Pitrou244651a2009-05-04 18:56:13 +00003489 if (inShift) { /* in a base-64 section */
3490 if (IS_BASE64(ch)) { /* consume a base-64 character */
3491 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3492 base64bits += 6;
3493 s++;
3494 if (base64bits >= 16) {
3495 /* we have enough bits for a UTF-16 value */
3496 Py_UNICODE outCh = (Py_UNICODE)
3497 (base64buffer >> (base64bits-16));
3498 base64bits -= 16;
3499 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3500 if (surrogate) {
3501 /* expecting a second surrogate */
3502 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3503#ifdef Py_UNICODE_WIDE
3504 *p++ = (((surrogate & 0x3FF)<<10)
3505 | (outCh & 0x3FF)) + 0x10000;
3506#else
3507 *p++ = surrogate;
3508 *p++ = outCh;
3509#endif
3510 surrogate = 0;
3511 }
3512 else {
3513 surrogate = 0;
3514 errmsg = "second surrogate missing";
3515 goto utf7Error;
3516 }
3517 }
3518 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3519 /* first surrogate */
3520 surrogate = outCh;
3521 }
3522 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3523 errmsg = "unexpected second surrogate";
3524 goto utf7Error;
3525 }
3526 else {
3527 *p++ = outCh;
3528 }
3529 }
3530 }
3531 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003532 inShift = 0;
3533 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003534 if (surrogate) {
3535 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003536 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003537 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003538 if (base64bits > 0) { /* left-over bits */
3539 if (base64bits >= 6) {
3540 /* We've seen at least one base-64 character */
3541 errmsg = "partial character in shift sequence";
3542 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003543 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003544 else {
3545 /* Some bits remain; they should be zero */
3546 if (base64buffer != 0) {
3547 errmsg = "non-zero padding bits in shift sequence";
3548 goto utf7Error;
3549 }
3550 }
3551 }
3552 if (ch != '-') {
3553 /* '-' is absorbed; other terminating
3554 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003555 *p++ = ch;
3556 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003557 }
3558 }
3559 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003560 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003561 s++; /* consume '+' */
3562 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003563 s++;
3564 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003565 }
3566 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003567 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003568 shiftOutStart = p;
3569 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003570 }
3571 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003572 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003573 *p++ = ch;
3574 s++;
3575 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003576 else {
3577 startinpos = s-starts;
3578 s++;
3579 errmsg = "unexpected special character";
3580 goto utf7Error;
3581 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003582 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003583utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003584 outpos = p-PyUnicode_AS_UNICODE(unicode);
3585 endinpos = s-starts;
3586 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003587 errors, &errorHandler,
3588 "utf7", errmsg,
3589 &starts, &e, &startinpos, &endinpos, &exc, &s,
3590 &unicode, &outpos, &p))
3591 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003592 }
3593
Antoine Pitrou244651a2009-05-04 18:56:13 +00003594 /* end of string */
3595
3596 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3597 /* if we're in an inconsistent state, that's an error */
3598 if (surrogate ||
3599 (base64bits >= 6) ||
3600 (base64bits > 0 && base64buffer != 0)) {
3601 outpos = p-PyUnicode_AS_UNICODE(unicode);
3602 endinpos = size;
3603 if (unicode_decode_call_errorhandler(
3604 errors, &errorHandler,
3605 "utf7", "unterminated shift sequence",
3606 &starts, &e, &startinpos, &endinpos, &exc, &s,
3607 &unicode, &outpos, &p))
3608 goto onError;
3609 if (s < e)
3610 goto restart;
3611 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003612 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003613
3614 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003615 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003616 if (inShift) {
3617 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003618 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003619 }
3620 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003621 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003622 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003623 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003624
Victor Stinnerfe226c02011-10-03 03:52:20 +02003625 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003626 goto onError;
3627
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003628 Py_XDECREF(errorHandler);
3629 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003630 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003631 Py_DECREF(unicode);
3632 return NULL;
3633 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003634 return (PyObject *)unicode;
3635
Benjamin Peterson29060642009-01-31 22:14:21 +00003636 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 Py_XDECREF(errorHandler);
3638 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003639 Py_DECREF(unicode);
3640 return NULL;
3641}
3642
3643
Alexander Belopolsky40018472011-02-26 01:02:56 +00003644PyObject *
3645PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003646 Py_ssize_t size,
3647 int base64SetO,
3648 int base64WhiteSpace,
3649 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003650{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003651 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003652 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003653 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003654 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003655 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003656 unsigned int base64bits = 0;
3657 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003658 char * out;
3659 char * start;
3660
3661 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003662 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003663
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003664 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003665 return PyErr_NoMemory();
3666
Antoine Pitrou244651a2009-05-04 18:56:13 +00003667 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003668 if (v == NULL)
3669 return NULL;
3670
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003671 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003672 for (;i < size; ++i) {
3673 Py_UNICODE ch = s[i];
3674
Antoine Pitrou244651a2009-05-04 18:56:13 +00003675 if (inShift) {
3676 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3677 /* shifting out */
3678 if (base64bits) { /* output remaining bits */
3679 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3680 base64buffer = 0;
3681 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003682 }
3683 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003684 /* Characters not in the BASE64 set implicitly unshift the sequence
3685 so no '-' is required, except if the character is itself a '-' */
3686 if (IS_BASE64(ch) || ch == '-') {
3687 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003688 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003689 *out++ = (char) ch;
3690 }
3691 else {
3692 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003693 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003694 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003695 else { /* not in a shift sequence */
3696 if (ch == '+') {
3697 *out++ = '+';
3698 *out++ = '-';
3699 }
3700 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3701 *out++ = (char) ch;
3702 }
3703 else {
3704 *out++ = '+';
3705 inShift = 1;
3706 goto encode_char;
3707 }
3708 }
3709 continue;
3710encode_char:
3711#ifdef Py_UNICODE_WIDE
3712 if (ch >= 0x10000) {
3713 /* code first surrogate */
3714 base64bits += 16;
3715 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
3716 while (base64bits >= 6) {
3717 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3718 base64bits -= 6;
3719 }
3720 /* prepare second surrogate */
3721 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
3722 }
3723#endif
3724 base64bits += 16;
3725 base64buffer = (base64buffer << 16) | ch;
3726 while (base64bits >= 6) {
3727 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
3728 base64bits -= 6;
3729 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00003730 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003731 if (base64bits)
3732 *out++= TO_BASE64(base64buffer << (6-base64bits) );
3733 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003734 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003735 if (_PyBytes_Resize(&v, out - start) < 0)
3736 return NULL;
3737 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003738}
3739
Antoine Pitrou244651a2009-05-04 18:56:13 +00003740#undef IS_BASE64
3741#undef FROM_BASE64
3742#undef TO_BASE64
3743#undef DECODE_DIRECT
3744#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003745
Guido van Rossumd57fd912000-03-10 22:53:23 +00003746/* --- UTF-8 Codec -------------------------------------------------------- */
3747
Tim Petersced69f82003-09-16 20:30:58 +00003748static
Guido van Rossumd57fd912000-03-10 22:53:23 +00003749char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00003750 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
3751 illegal prefix. See RFC 3629 for details */
3752 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
3753 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003754 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00003755 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3756 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3757 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3758 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00003759 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
3760 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 +00003761 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3762 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00003763 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
3764 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
3765 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
3766 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
3767 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 +00003768};
3769
Alexander Belopolsky40018472011-02-26 01:02:56 +00003770PyObject *
3771PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003772 Py_ssize_t size,
3773 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003774{
Walter Dörwald69652032004-09-07 20:24:22 +00003775 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3776}
3777
Antoine Pitrouab868312009-01-10 15:40:25 +00003778/* Mask to check or force alignment of a pointer to C 'long' boundaries */
3779#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
3780
3781/* Mask to quickly check whether a C 'long' contains a
3782 non-ASCII, UTF8-encoded char. */
3783#if (SIZEOF_LONG == 8)
3784# define ASCII_CHAR_MASK 0x8080808080808080L
3785#elif (SIZEOF_LONG == 4)
3786# define ASCII_CHAR_MASK 0x80808080L
3787#else
3788# error C 'long' size should be either 4 or 8!
3789#endif
3790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791/* Scans a UTF-8 string and returns the maximum character to be expected,
3792 the size of the decoded unicode string and if any major errors were
3793 encountered.
3794
3795 This function does check basic UTF-8 sanity, it does however NOT CHECK
3796 if the string contains surrogates, and if all continuation bytes are
3797 within the correct ranges, these checks are performed in
3798 PyUnicode_DecodeUTF8Stateful.
3799
3800 If it sets has_errors to 1, it means the value of unicode_size and max_char
3801 will be bogus and you should not rely on useful information in them.
3802 */
3803static Py_UCS4
3804utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
3805 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
3806 int *has_errors)
3807{
3808 Py_ssize_t n;
3809 Py_ssize_t char_count = 0;
3810 Py_UCS4 max_char = 127, new_max;
3811 Py_UCS4 upper_bound;
3812 const unsigned char *p = (const unsigned char *)s;
3813 const unsigned char *end = p + string_size;
3814 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
3815 int err = 0;
3816
3817 for (; p < end && !err; ++p, ++char_count) {
3818 /* Only check value if it's not a ASCII char... */
3819 if (*p < 0x80) {
3820 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
3821 an explanation. */
3822 if (!((size_t) p & LONG_PTR_MASK)) {
3823 /* Help register allocation */
3824 register const unsigned char *_p = p;
3825 while (_p < aligned_end) {
3826 unsigned long value = *(unsigned long *) _p;
3827 if (value & ASCII_CHAR_MASK)
3828 break;
3829 _p += SIZEOF_LONG;
3830 char_count += SIZEOF_LONG;
3831 }
3832 p = _p;
3833 if (p == end)
3834 break;
3835 }
3836 }
3837 if (*p >= 0x80) {
3838 n = utf8_code_length[*p];
3839 new_max = max_char;
3840 switch (n) {
3841 /* invalid start byte */
3842 case 0:
3843 err = 1;
3844 break;
3845 case 2:
3846 /* Code points between 0x00FF and 0x07FF inclusive.
3847 Approximate the upper bound of the code point,
3848 if this flips over 255 we can be sure it will be more
3849 than 255 and the string will need 2 bytes per code coint,
3850 if it stays under or equal to 255, we can be sure 1 byte
3851 is enough.
3852 ((*p & 0b00011111) << 6) | 0b00111111 */
3853 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
3854 if (max_char < upper_bound)
3855 new_max = upper_bound;
3856 /* Ensure we track at least that we left ASCII space. */
3857 if (new_max < 128)
3858 new_max = 128;
3859 break;
3860 case 3:
3861 /* Between 0x0FFF and 0xFFFF inclusive, so values are
3862 always > 255 and <= 65535 and will always need 2 bytes. */
3863 if (max_char < 65535)
3864 new_max = 65535;
3865 break;
3866 case 4:
3867 /* Code point will be above 0xFFFF for sure in this case. */
3868 new_max = 65537;
3869 break;
3870 /* Internal error, this should be caught by the first if */
3871 case 1:
3872 default:
3873 assert(0 && "Impossible case in utf8_max_char_and_size");
3874 err = 1;
3875 }
3876 /* Instead of number of overall bytes for this code point,
3877 n containts the number of following bytes: */
3878 --n;
3879 /* Check if the follow up chars are all valid continuation bytes */
3880 if (n >= 1) {
3881 const unsigned char *cont;
3882 if ((p + n) >= end) {
3883 if (consumed == 0)
3884 /* incomplete data, non-incremental decoding */
3885 err = 1;
3886 break;
3887 }
3888 for (cont = p + 1; cont < (p + n); ++cont) {
3889 if ((*cont & 0xc0) != 0x80) {
3890 err = 1;
3891 break;
3892 }
3893 }
3894 p += n;
3895 }
3896 else
3897 err = 1;
3898 max_char = new_max;
3899 }
3900 }
3901
3902 if (unicode_size)
3903 *unicode_size = char_count;
3904 if (has_errors)
3905 *has_errors = err;
3906 return max_char;
3907}
3908
3909/* Similar to PyUnicode_WRITE but can also write into wstr field
3910 of the legacy unicode representation */
3911#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
3912 do { \
3913 const int k_ = (kind); \
3914 if (k_ == PyUnicode_WCHAR_KIND) \
3915 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
3916 else if (k_ == PyUnicode_1BYTE_KIND) \
3917 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
3918 else if (k_ == PyUnicode_2BYTE_KIND) \
3919 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
3920 else \
3921 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
3922 } while (0)
3923
Alexander Belopolsky40018472011-02-26 01:02:56 +00003924PyObject *
3925PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 Py_ssize_t size,
3927 const char *errors,
3928 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00003929{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003930 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003931 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00003932 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003933 Py_ssize_t startinpos;
3934 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00003935 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003936 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00003937 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003938 PyObject *errorHandler = NULL;
3939 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940 Py_UCS4 maxchar = 0;
3941 Py_ssize_t unicode_size;
3942 Py_ssize_t i;
3943 int kind;
3944 void *data;
3945 int has_errors;
3946 Py_UNICODE *error_outptr;
3947#if SIZEOF_WCHAR_T == 2
3948 Py_ssize_t wchar_offset = 0;
3949#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00003950
Walter Dörwald69652032004-09-07 20:24:22 +00003951 if (size == 0) {
3952 if (consumed)
3953 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00003955 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
3957 consumed, &has_errors);
3958 if (has_errors) {
3959 unicode = _PyUnicode_New(size);
3960 if (!unicode)
3961 return NULL;
3962 kind = PyUnicode_WCHAR_KIND;
3963 data = PyUnicode_AS_UNICODE(unicode);
3964 assert(data != NULL);
3965 }
3966 else {
3967 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
3968 if (!unicode)
3969 return NULL;
3970 /* When the string is ASCII only, just use memcpy and return.
3971 unicode_size may be != size if there is an incomplete UTF-8
3972 sequence at the end of the ASCII block. */
3973 if (maxchar < 128 && size == unicode_size) {
3974 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
3975 return (PyObject *)unicode;
3976 }
3977 kind = PyUnicode_KIND(unicode);
3978 data = PyUnicode_DATA(unicode);
3979 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003980 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003982 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00003983 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003984
3985 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00003986 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003987
3988 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00003989 /* Fast path for runs of ASCII characters. Given that common UTF-8
3990 input will consist of an overwhelming majority of ASCII
3991 characters, we try to optimize for this case by checking
3992 as many characters as a C 'long' can contain.
3993 First, check if we can do an aligned read, as most CPUs have
3994 a penalty for unaligned reads.
3995 */
3996 if (!((size_t) s & LONG_PTR_MASK)) {
3997 /* Help register allocation */
3998 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004000 while (_s < aligned_end) {
4001 /* Read a whole long at a time (either 4 or 8 bytes),
4002 and do a fast unrolled copy if it only contains ASCII
4003 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004 unsigned long value = *(unsigned long *) _s;
4005 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004006 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004007 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4008 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4009 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4010 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004011#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004012 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4013 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4014 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4015 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004016#endif
4017 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004018 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004019 }
4020 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004021 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004022 if (s == e)
4023 break;
4024 ch = (unsigned char)*s;
4025 }
4026 }
4027
4028 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004030 s++;
4031 continue;
4032 }
4033
4034 n = utf8_code_length[ch];
4035
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004036 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 if (consumed)
4038 break;
4039 else {
4040 errmsg = "unexpected end of data";
4041 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004042 endinpos = startinpos+1;
4043 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4044 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004045 goto utf8Error;
4046 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004048
4049 switch (n) {
4050
4051 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004052 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004053 startinpos = s-starts;
4054 endinpos = startinpos+1;
4055 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004056
4057 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004058 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 startinpos = s-starts;
4060 endinpos = startinpos+1;
4061 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004062
4063 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004064 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004065 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004066 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004067 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004068 goto utf8Error;
4069 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004070 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004071 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004072 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004073 break;
4074
4075 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004076 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4077 will result in surrogates in range d800-dfff. Surrogates are
4078 not valid UTF-8 so they are rejected.
4079 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4080 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004081 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004082 (s[2] & 0xc0) != 0x80 ||
4083 ((unsigned char)s[0] == 0xE0 &&
4084 (unsigned char)s[1] < 0xA0) ||
4085 ((unsigned char)s[0] == 0xED &&
4086 (unsigned char)s[1] > 0x9F)) {
4087 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004088 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004089 endinpos = startinpos + 1;
4090
4091 /* if s[1] first two bits are 1 and 0, then the invalid
4092 continuation byte is s[2], so increment endinpos by 1,
4093 if not, s[1] is invalid and endinpos doesn't need to
4094 be incremented. */
4095 if ((s[1] & 0xC0) == 0x80)
4096 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004097 goto utf8Error;
4098 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004099 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004100 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004101 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004102 break;
4103
4104 case 4:
4105 if ((s[1] & 0xc0) != 0x80 ||
4106 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004107 (s[3] & 0xc0) != 0x80 ||
4108 ((unsigned char)s[0] == 0xF0 &&
4109 (unsigned char)s[1] < 0x90) ||
4110 ((unsigned char)s[0] == 0xF4 &&
4111 (unsigned char)s[1] > 0x8F)) {
4112 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004114 endinpos = startinpos + 1;
4115 if ((s[1] & 0xC0) == 0x80) {
4116 endinpos++;
4117 if ((s[2] & 0xC0) == 0x80)
4118 endinpos++;
4119 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004120 goto utf8Error;
4121 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004122 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004123 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4124 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004126 /* If the string is flexible or we have native UCS-4, write
4127 directly.. */
4128 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4129 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004131 else {
4132 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004134 /* translate from 10000..10FFFF to 0..FFFF */
4135 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004137 /* high surrogate = top 10 bits added to D800 */
4138 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4139 (Py_UNICODE)(0xD800 + (ch >> 10)));
4140
4141 /* low surrogate = bottom 10 bits added to DC00 */
4142 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4143 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4144 }
4145#if SIZEOF_WCHAR_T == 2
4146 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004147#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004148 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149 }
4150 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004151 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004152
Benjamin Peterson29060642009-01-31 22:14:21 +00004153 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004154 /* If this is not yet a resizable string, make it one.. */
4155 if (kind != PyUnicode_WCHAR_KIND) {
4156 const Py_UNICODE *u;
4157 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4158 if (!new_unicode)
4159 goto onError;
4160 u = PyUnicode_AsUnicode((PyObject *)unicode);
4161 if (!u)
4162 goto onError;
4163#if SIZEOF_WCHAR_T == 2
4164 i += wchar_offset;
4165#endif
4166 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4167 Py_DECREF(unicode);
4168 unicode = new_unicode;
4169 kind = 0;
4170 data = PyUnicode_AS_UNICODE(new_unicode);
4171 assert(data != NULL);
4172 }
4173 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 if (unicode_decode_call_errorhandler(
4175 errors, &errorHandler,
4176 "utf8", errmsg,
4177 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004178 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004179 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004180 /* Update data because unicode_decode_call_errorhandler might have
4181 re-created or resized the unicode object. */
4182 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004183 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004184 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004185 /* Ensure the unicode_size calculation above was correct: */
4186 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4187
Walter Dörwald69652032004-09-07 20:24:22 +00004188 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004189 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004191 /* Adjust length and ready string when it contained errors and
4192 is of the old resizable kind. */
4193 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004194 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004195 goto onError;
4196 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004197
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004198 Py_XDECREF(errorHandler);
4199 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004200 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004201 Py_DECREF(unicode);
4202 return NULL;
4203 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004204 return (PyObject *)unicode;
4205
Benjamin Peterson29060642009-01-31 22:14:21 +00004206 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004207 Py_XDECREF(errorHandler);
4208 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004209 Py_DECREF(unicode);
4210 return NULL;
4211}
4212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004213#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004214
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004215#ifdef __APPLE__
4216
4217/* Simplified UTF-8 decoder using surrogateescape error handler,
4218 used to decode the command line arguments on Mac OS X. */
4219
4220wchar_t*
4221_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4222{
4223 int n;
4224 const char *e;
4225 wchar_t *unicode, *p;
4226
4227 /* Note: size will always be longer than the resulting Unicode
4228 character count */
4229 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4230 PyErr_NoMemory();
4231 return NULL;
4232 }
4233 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4234 if (!unicode)
4235 return NULL;
4236
4237 /* Unpack UTF-8 encoded data */
4238 p = unicode;
4239 e = s + size;
4240 while (s < e) {
4241 Py_UCS4 ch = (unsigned char)*s;
4242
4243 if (ch < 0x80) {
4244 *p++ = (wchar_t)ch;
4245 s++;
4246 continue;
4247 }
4248
4249 n = utf8_code_length[ch];
4250 if (s + n > e) {
4251 goto surrogateescape;
4252 }
4253
4254 switch (n) {
4255 case 0:
4256 case 1:
4257 goto surrogateescape;
4258
4259 case 2:
4260 if ((s[1] & 0xc0) != 0x80)
4261 goto surrogateescape;
4262 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4263 assert ((ch > 0x007F) && (ch <= 0x07FF));
4264 *p++ = (wchar_t)ch;
4265 break;
4266
4267 case 3:
4268 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4269 will result in surrogates in range d800-dfff. Surrogates are
4270 not valid UTF-8 so they are rejected.
4271 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4272 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4273 if ((s[1] & 0xc0) != 0x80 ||
4274 (s[2] & 0xc0) != 0x80 ||
4275 ((unsigned char)s[0] == 0xE0 &&
4276 (unsigned char)s[1] < 0xA0) ||
4277 ((unsigned char)s[0] == 0xED &&
4278 (unsigned char)s[1] > 0x9F)) {
4279
4280 goto surrogateescape;
4281 }
4282 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4283 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004284 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004285 break;
4286
4287 case 4:
4288 if ((s[1] & 0xc0) != 0x80 ||
4289 (s[2] & 0xc0) != 0x80 ||
4290 (s[3] & 0xc0) != 0x80 ||
4291 ((unsigned char)s[0] == 0xF0 &&
4292 (unsigned char)s[1] < 0x90) ||
4293 ((unsigned char)s[0] == 0xF4 &&
4294 (unsigned char)s[1] > 0x8F)) {
4295 goto surrogateescape;
4296 }
4297 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4298 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4299 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4300
4301#if SIZEOF_WCHAR_T == 4
4302 *p++ = (wchar_t)ch;
4303#else
4304 /* compute and append the two surrogates: */
4305
4306 /* translate from 10000..10FFFF to 0..FFFF */
4307 ch -= 0x10000;
4308
4309 /* high surrogate = top 10 bits added to D800 */
4310 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4311
4312 /* low surrogate = bottom 10 bits added to DC00 */
4313 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4314#endif
4315 break;
4316 }
4317 s += n;
4318 continue;
4319
4320 surrogateescape:
4321 *p++ = 0xDC00 + ch;
4322 s++;
4323 }
4324 *p = L'\0';
4325 return unicode;
4326}
4327
4328#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004330/* Primary internal function which creates utf8 encoded bytes objects.
4331
4332 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004333 and allocate exactly as much space needed at the end. Else allocate the
4334 maximum possible needed (4 result bytes per Unicode character), and return
4335 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004336*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004337PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004338_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004339{
Tim Peters602f7402002-04-27 18:03:26 +00004340#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004341
Guido van Rossum98297ee2007-11-06 21:34:58 +00004342 Py_ssize_t i; /* index into s of next input byte */
4343 PyObject *result; /* result string object */
4344 char *p; /* next free byte in output buffer */
4345 Py_ssize_t nallocated; /* number of result bytes allocated */
4346 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004347 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004348 PyObject *errorHandler = NULL;
4349 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004350 int kind;
4351 void *data;
4352 Py_ssize_t size;
4353 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4354#if SIZEOF_WCHAR_T == 2
4355 Py_ssize_t wchar_offset = 0;
4356#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004357
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004358 if (!PyUnicode_Check(unicode)) {
4359 PyErr_BadArgument();
4360 return NULL;
4361 }
4362
4363 if (PyUnicode_READY(unicode) == -1)
4364 return NULL;
4365
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004366 if (PyUnicode_UTF8(unicode))
4367 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4368 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004369
4370 kind = PyUnicode_KIND(unicode);
4371 data = PyUnicode_DATA(unicode);
4372 size = PyUnicode_GET_LENGTH(unicode);
4373
Tim Peters602f7402002-04-27 18:03:26 +00004374 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004375
Tim Peters602f7402002-04-27 18:03:26 +00004376 if (size <= MAX_SHORT_UNICHARS) {
4377 /* Write into the stack buffer; nallocated can't overflow.
4378 * At the end, we'll allocate exactly as much heap space as it
4379 * turns out we need.
4380 */
4381 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004382 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004383 p = stackbuf;
4384 }
4385 else {
4386 /* Overallocate on the heap, and give the excess back at the end. */
4387 nallocated = size * 4;
4388 if (nallocated / 4 != size) /* overflow! */
4389 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004390 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004391 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004392 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004393 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004394 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004395
Tim Peters602f7402002-04-27 18:03:26 +00004396 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004397 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004398
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004399 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004400 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004401 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004402
Guido van Rossumd57fd912000-03-10 22:53:23 +00004403 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004404 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004405 *p++ = (char)(0xc0 | (ch >> 6));
4406 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004407 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004408 Py_ssize_t newpos;
4409 PyObject *rep;
4410 Py_ssize_t repsize, k, startpos;
4411 startpos = i-1;
4412#if SIZEOF_WCHAR_T == 2
4413 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004414#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004415 rep = unicode_encode_call_errorhandler(
4416 errors, &errorHandler, "utf-8", "surrogates not allowed",
4417 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4418 &exc, startpos, startpos+1, &newpos);
4419 if (!rep)
4420 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004422 if (PyBytes_Check(rep))
4423 repsize = PyBytes_GET_SIZE(rep);
4424 else
4425 repsize = PyUnicode_GET_SIZE(rep);
4426
4427 if (repsize > 4) {
4428 Py_ssize_t offset;
4429
4430 if (result == NULL)
4431 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004432 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004433 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004435 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4436 /* integer overflow */
4437 PyErr_NoMemory();
4438 goto error;
4439 }
4440 nallocated += repsize - 4;
4441 if (result != NULL) {
4442 if (_PyBytes_Resize(&result, nallocated) < 0)
4443 goto error;
4444 } else {
4445 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004446 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004447 goto error;
4448 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4449 }
4450 p = PyBytes_AS_STRING(result) + offset;
4451 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004453 if (PyBytes_Check(rep)) {
4454 char *prep = PyBytes_AS_STRING(rep);
4455 for(k = repsize; k > 0; k--)
4456 *p++ = *prep++;
4457 } else /* rep is unicode */ {
4458 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4459 Py_UNICODE c;
4460
4461 for(k=0; k<repsize; k++) {
4462 c = prep[k];
4463 if (0x80 <= c) {
4464 raise_encode_exception(&exc, "utf-8",
4465 PyUnicode_AS_UNICODE(unicode),
4466 size, i-1, i,
4467 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004468 goto error;
4469 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004470 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004471 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004472 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004473 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004474 } else if (ch < 0x10000) {
4475 *p++ = (char)(0xe0 | (ch >> 12));
4476 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4477 *p++ = (char)(0x80 | (ch & 0x3f));
4478 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004479 /* Encode UCS4 Unicode ordinals */
4480 *p++ = (char)(0xf0 | (ch >> 18));
4481 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4482 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4483 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004484#if SIZEOF_WCHAR_T == 2
4485 wchar_offset++;
4486#endif
Tim Peters602f7402002-04-27 18:03:26 +00004487 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004488 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004489
Guido van Rossum98297ee2007-11-06 21:34:58 +00004490 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004491 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004492 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004493 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004494 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004495 }
4496 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004497 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004498 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004499 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004500 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004501 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004502
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004503 Py_XDECREF(errorHandler);
4504 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004505 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004506 error:
4507 Py_XDECREF(errorHandler);
4508 Py_XDECREF(exc);
4509 Py_XDECREF(result);
4510 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004511
Tim Peters602f7402002-04-27 18:03:26 +00004512#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004513}
4514
Alexander Belopolsky40018472011-02-26 01:02:56 +00004515PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004516PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4517 Py_ssize_t size,
4518 const char *errors)
4519{
4520 PyObject *v, *unicode;
4521
4522 unicode = PyUnicode_FromUnicode(s, size);
4523 if (unicode == NULL)
4524 return NULL;
4525 v = _PyUnicode_AsUTF8String(unicode, errors);
4526 Py_DECREF(unicode);
4527 return v;
4528}
4529
4530PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004531PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004533 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004534}
4535
Walter Dörwald41980ca2007-08-16 21:55:45 +00004536/* --- UTF-32 Codec ------------------------------------------------------- */
4537
4538PyObject *
4539PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004540 Py_ssize_t size,
4541 const char *errors,
4542 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004543{
4544 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4545}
4546
4547PyObject *
4548PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004549 Py_ssize_t size,
4550 const char *errors,
4551 int *byteorder,
4552 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004553{
4554 const char *starts = s;
4555 Py_ssize_t startinpos;
4556 Py_ssize_t endinpos;
4557 Py_ssize_t outpos;
4558 PyUnicodeObject *unicode;
4559 Py_UNICODE *p;
4560#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004561 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004562 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004563#else
4564 const int pairs = 0;
4565#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004566 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004567 int bo = 0; /* assume native ordering by default */
4568 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004569 /* Offsets from q for retrieving bytes in the right order. */
4570#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4571 int iorder[] = {0, 1, 2, 3};
4572#else
4573 int iorder[] = {3, 2, 1, 0};
4574#endif
4575 PyObject *errorHandler = NULL;
4576 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004577
Walter Dörwald41980ca2007-08-16 21:55:45 +00004578 q = (unsigned char *)s;
4579 e = q + size;
4580
4581 if (byteorder)
4582 bo = *byteorder;
4583
4584 /* Check for BOM marks (U+FEFF) in the input and adjust current
4585 byte order setting accordingly. In native mode, the leading BOM
4586 mark is skipped, in all other modes, it is copied to the output
4587 stream as-is (giving a ZWNBSP character). */
4588 if (bo == 0) {
4589 if (size >= 4) {
4590 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004591 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004592#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004593 if (bom == 0x0000FEFF) {
4594 q += 4;
4595 bo = -1;
4596 }
4597 else if (bom == 0xFFFE0000) {
4598 q += 4;
4599 bo = 1;
4600 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004601#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004602 if (bom == 0x0000FEFF) {
4603 q += 4;
4604 bo = 1;
4605 }
4606 else if (bom == 0xFFFE0000) {
4607 q += 4;
4608 bo = -1;
4609 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004610#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004611 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004612 }
4613
4614 if (bo == -1) {
4615 /* force LE */
4616 iorder[0] = 0;
4617 iorder[1] = 1;
4618 iorder[2] = 2;
4619 iorder[3] = 3;
4620 }
4621 else if (bo == 1) {
4622 /* force BE */
4623 iorder[0] = 3;
4624 iorder[1] = 2;
4625 iorder[2] = 1;
4626 iorder[3] = 0;
4627 }
4628
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004629 /* On narrow builds we split characters outside the BMP into two
4630 codepoints => count how much extra space we need. */
4631#ifndef Py_UNICODE_WIDE
4632 for (qq = q; qq < e; qq += 4)
4633 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4634 pairs++;
4635#endif
4636
4637 /* This might be one to much, because of a BOM */
4638 unicode = _PyUnicode_New((size+3)/4+pairs);
4639 if (!unicode)
4640 return NULL;
4641 if (size == 0)
4642 return (PyObject *)unicode;
4643
4644 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004645 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004646
Walter Dörwald41980ca2007-08-16 21:55:45 +00004647 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004648 Py_UCS4 ch;
4649 /* remaining bytes at the end? (size should be divisible by 4) */
4650 if (e-q<4) {
4651 if (consumed)
4652 break;
4653 errmsg = "truncated data";
4654 startinpos = ((const char *)q)-starts;
4655 endinpos = ((const char *)e)-starts;
4656 goto utf32Error;
4657 /* The remaining input chars are ignored if the callback
4658 chooses to skip the input */
4659 }
4660 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4661 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004662
Benjamin Peterson29060642009-01-31 22:14:21 +00004663 if (ch >= 0x110000)
4664 {
4665 errmsg = "codepoint not in range(0x110000)";
4666 startinpos = ((const char *)q)-starts;
4667 endinpos = startinpos+4;
4668 goto utf32Error;
4669 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004670#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004671 if (ch >= 0x10000)
4672 {
4673 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4674 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4675 }
4676 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004677#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004678 *p++ = ch;
4679 q += 4;
4680 continue;
4681 utf32Error:
4682 outpos = p-PyUnicode_AS_UNICODE(unicode);
4683 if (unicode_decode_call_errorhandler(
4684 errors, &errorHandler,
4685 "utf32", errmsg,
4686 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4687 &unicode, &outpos, &p))
4688 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004689 }
4690
4691 if (byteorder)
4692 *byteorder = bo;
4693
4694 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004695 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004696
4697 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02004698 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004699 goto onError;
4700
4701 Py_XDECREF(errorHandler);
4702 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004703 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004704 Py_DECREF(unicode);
4705 return NULL;
4706 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004707 return (PyObject *)unicode;
4708
Benjamin Peterson29060642009-01-31 22:14:21 +00004709 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00004710 Py_DECREF(unicode);
4711 Py_XDECREF(errorHandler);
4712 Py_XDECREF(exc);
4713 return NULL;
4714}
4715
4716PyObject *
4717PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004718 Py_ssize_t size,
4719 const char *errors,
4720 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004721{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004722 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004723 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004724 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004725#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004726 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004727#else
4728 const int pairs = 0;
4729#endif
4730 /* Offsets from p for storing byte pairs in the right order. */
4731#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4732 int iorder[] = {0, 1, 2, 3};
4733#else
4734 int iorder[] = {3, 2, 1, 0};
4735#endif
4736
Benjamin Peterson29060642009-01-31 22:14:21 +00004737#define STORECHAR(CH) \
4738 do { \
4739 p[iorder[3]] = ((CH) >> 24) & 0xff; \
4740 p[iorder[2]] = ((CH) >> 16) & 0xff; \
4741 p[iorder[1]] = ((CH) >> 8) & 0xff; \
4742 p[iorder[0]] = (CH) & 0xff; \
4743 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00004744 } while(0)
4745
4746 /* In narrow builds we can output surrogate pairs as one codepoint,
4747 so we need less space. */
4748#ifndef Py_UNICODE_WIDE
4749 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
4751 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
4752 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004753#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004754 nsize = (size - pairs + (byteorder == 0));
4755 bytesize = nsize * 4;
4756 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00004757 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004758 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004759 if (v == NULL)
4760 return NULL;
4761
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004762 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004763 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004764 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004765 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00004766 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004767
4768 if (byteorder == -1) {
4769 /* force LE */
4770 iorder[0] = 0;
4771 iorder[1] = 1;
4772 iorder[2] = 2;
4773 iorder[3] = 3;
4774 }
4775 else if (byteorder == 1) {
4776 /* force BE */
4777 iorder[0] = 3;
4778 iorder[1] = 2;
4779 iorder[2] = 1;
4780 iorder[3] = 0;
4781 }
4782
4783 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004784 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004785#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004786 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
4787 Py_UCS4 ch2 = *s;
4788 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
4789 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
4790 s++;
4791 size--;
4792 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004793 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004794#endif
4795 STORECHAR(ch);
4796 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00004797
4798 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004799 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004800#undef STORECHAR
4801}
4802
Alexander Belopolsky40018472011-02-26 01:02:56 +00004803PyObject *
4804PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004805{
4806 if (!PyUnicode_Check(unicode)) {
4807 PyErr_BadArgument();
4808 return NULL;
4809 }
4810 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00004811 PyUnicode_GET_SIZE(unicode),
4812 NULL,
4813 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00004814}
4815
Guido van Rossumd57fd912000-03-10 22:53:23 +00004816/* --- UTF-16 Codec ------------------------------------------------------- */
4817
Tim Peters772747b2001-08-09 22:21:55 +00004818PyObject *
4819PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004820 Py_ssize_t size,
4821 const char *errors,
4822 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004823{
Walter Dörwald69652032004-09-07 20:24:22 +00004824 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
4825}
4826
Antoine Pitrouab868312009-01-10 15:40:25 +00004827/* Two masks for fast checking of whether a C 'long' may contain
4828 UTF16-encoded surrogate characters. This is an efficient heuristic,
4829 assuming that non-surrogate characters with a code point >= 0x8000 are
4830 rare in most input.
4831 FAST_CHAR_MASK is used when the input is in native byte ordering,
4832 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00004833*/
Antoine Pitrouab868312009-01-10 15:40:25 +00004834#if (SIZEOF_LONG == 8)
4835# define FAST_CHAR_MASK 0x8000800080008000L
4836# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
4837#elif (SIZEOF_LONG == 4)
4838# define FAST_CHAR_MASK 0x80008000L
4839# define SWAPPED_FAST_CHAR_MASK 0x00800080L
4840#else
4841# error C 'long' size should be either 4 or 8!
4842#endif
4843
Walter Dörwald69652032004-09-07 20:24:22 +00004844PyObject *
4845PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 Py_ssize_t size,
4847 const char *errors,
4848 int *byteorder,
4849 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004850{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004851 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004852 Py_ssize_t startinpos;
4853 Py_ssize_t endinpos;
4854 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855 PyUnicodeObject *unicode;
4856 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00004857 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00004858 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00004859 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004860 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00004861 /* Offsets from q for retrieving byte pairs in the right order. */
4862#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4863 int ihi = 1, ilo = 0;
4864#else
4865 int ihi = 0, ilo = 1;
4866#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004867 PyObject *errorHandler = NULL;
4868 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004869
4870 /* Note: size will always be longer than the resulting Unicode
4871 character count */
4872 unicode = _PyUnicode_New(size);
4873 if (!unicode)
4874 return NULL;
4875 if (size == 0)
4876 return (PyObject *)unicode;
4877
4878 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004879 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00004880 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00004881 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004882
4883 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00004884 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004886 /* Check for BOM marks (U+FEFF) in the input and adjust current
4887 byte order setting accordingly. In native mode, the leading BOM
4888 mark is skipped, in all other modes, it is copied to the output
4889 stream as-is (giving a ZWNBSP character). */
4890 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00004891 if (size >= 2) {
4892 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004893#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004894 if (bom == 0xFEFF) {
4895 q += 2;
4896 bo = -1;
4897 }
4898 else if (bom == 0xFFFE) {
4899 q += 2;
4900 bo = 1;
4901 }
Tim Petersced69f82003-09-16 20:30:58 +00004902#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004903 if (bom == 0xFEFF) {
4904 q += 2;
4905 bo = 1;
4906 }
4907 else if (bom == 0xFFFE) {
4908 q += 2;
4909 bo = -1;
4910 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004911#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004912 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00004913 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004914
Tim Peters772747b2001-08-09 22:21:55 +00004915 if (bo == -1) {
4916 /* force LE */
4917 ihi = 1;
4918 ilo = 0;
4919 }
4920 else if (bo == 1) {
4921 /* force BE */
4922 ihi = 0;
4923 ilo = 1;
4924 }
Antoine Pitrouab868312009-01-10 15:40:25 +00004925#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4926 native_ordering = ilo < ihi;
4927#else
4928 native_ordering = ilo > ihi;
4929#endif
Tim Peters772747b2001-08-09 22:21:55 +00004930
Antoine Pitrouab868312009-01-10 15:40:25 +00004931 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00004932 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004933 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00004934 /* First check for possible aligned read of a C 'long'. Unaligned
4935 reads are more expensive, better to defer to another iteration. */
4936 if (!((size_t) q & LONG_PTR_MASK)) {
4937 /* Fast path for runs of non-surrogate chars. */
4938 register const unsigned char *_q = q;
4939 Py_UNICODE *_p = p;
4940 if (native_ordering) {
4941 /* Native ordering is simple: as long as the input cannot
4942 possibly contain a surrogate char, do an unrolled copy
4943 of several 16-bit code points to the target object.
4944 The non-surrogate check is done on several input bytes
4945 at a time (as many as a C 'long' can contain). */
4946 while (_q < aligned_end) {
4947 unsigned long data = * (unsigned long *) _q;
4948 if (data & FAST_CHAR_MASK)
4949 break;
4950 _p[0] = ((unsigned short *) _q)[0];
4951 _p[1] = ((unsigned short *) _q)[1];
4952#if (SIZEOF_LONG == 8)
4953 _p[2] = ((unsigned short *) _q)[2];
4954 _p[3] = ((unsigned short *) _q)[3];
4955#endif
4956 _q += SIZEOF_LONG;
4957 _p += SIZEOF_LONG / 2;
4958 }
4959 }
4960 else {
4961 /* Byteswapped ordering is similar, but we must decompose
4962 the copy bytewise, and take care of zero'ing out the
4963 upper bytes if the target object is in 32-bit units
4964 (that is, in UCS-4 builds). */
4965 while (_q < aligned_end) {
4966 unsigned long data = * (unsigned long *) _q;
4967 if (data & SWAPPED_FAST_CHAR_MASK)
4968 break;
4969 /* Zero upper bytes in UCS-4 builds */
4970#if (Py_UNICODE_SIZE > 2)
4971 _p[0] = 0;
4972 _p[1] = 0;
4973#if (SIZEOF_LONG == 8)
4974 _p[2] = 0;
4975 _p[3] = 0;
4976#endif
4977#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004978 /* Issue #4916; UCS-4 builds on big endian machines must
4979 fill the two last bytes of each 4-byte unit. */
4980#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
4981# define OFF 2
4982#else
4983# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00004984#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00004985 ((unsigned char *) _p)[OFF + 1] = _q[0];
4986 ((unsigned char *) _p)[OFF + 0] = _q[1];
4987 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
4988 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
4989#if (SIZEOF_LONG == 8)
4990 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
4991 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
4992 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
4993 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
4994#endif
4995#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00004996 _q += SIZEOF_LONG;
4997 _p += SIZEOF_LONG / 2;
4998 }
4999 }
5000 p = _p;
5001 q = _q;
5002 if (q >= e)
5003 break;
5004 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005005 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005006
Benjamin Peterson14339b62009-01-31 16:36:08 +00005007 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005008
5009 if (ch < 0xD800 || ch > 0xDFFF) {
5010 *p++ = ch;
5011 continue;
5012 }
5013
5014 /* UTF-16 code pair: */
5015 if (q > e) {
5016 errmsg = "unexpected end of data";
5017 startinpos = (((const char *)q) - 2) - starts;
5018 endinpos = ((const char *)e) + 1 - starts;
5019 goto utf16Error;
5020 }
5021 if (0xD800 <= ch && ch <= 0xDBFF) {
5022 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5023 q += 2;
5024 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005025#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005026 *p++ = ch;
5027 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005028#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005030#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 continue;
5032 }
5033 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005034 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005035 startinpos = (((const char *)q)-4)-starts;
5036 endinpos = startinpos+2;
5037 goto utf16Error;
5038 }
5039
Benjamin Peterson14339b62009-01-31 16:36:08 +00005040 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 errmsg = "illegal encoding";
5042 startinpos = (((const char *)q)-2)-starts;
5043 endinpos = startinpos+2;
5044 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005045
Benjamin Peterson29060642009-01-31 22:14:21 +00005046 utf16Error:
5047 outpos = p - PyUnicode_AS_UNICODE(unicode);
5048 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005049 errors,
5050 &errorHandler,
5051 "utf16", errmsg,
5052 &starts,
5053 (const char **)&e,
5054 &startinpos,
5055 &endinpos,
5056 &exc,
5057 (const char **)&q,
5058 &unicode,
5059 &outpos,
5060 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005061 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005062 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005063 /* remaining byte at the end? (size should be even) */
5064 if (e == q) {
5065 if (!consumed) {
5066 errmsg = "truncated data";
5067 startinpos = ((const char *)q) - starts;
5068 endinpos = ((const char *)e) + 1 - starts;
5069 outpos = p - PyUnicode_AS_UNICODE(unicode);
5070 if (unicode_decode_call_errorhandler(
5071 errors,
5072 &errorHandler,
5073 "utf16", errmsg,
5074 &starts,
5075 (const char **)&e,
5076 &startinpos,
5077 &endinpos,
5078 &exc,
5079 (const char **)&q,
5080 &unicode,
5081 &outpos,
5082 &p))
5083 goto onError;
5084 /* The remaining input chars are ignored if the callback
5085 chooses to skip the input */
5086 }
5087 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005088
5089 if (byteorder)
5090 *byteorder = bo;
5091
Walter Dörwald69652032004-09-07 20:24:22 +00005092 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005094
Guido van Rossumd57fd912000-03-10 22:53:23 +00005095 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005096 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005097 goto onError;
5098
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005099 Py_XDECREF(errorHandler);
5100 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005101 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005102 Py_DECREF(unicode);
5103 return NULL;
5104 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005105 return (PyObject *)unicode;
5106
Benjamin Peterson29060642009-01-31 22:14:21 +00005107 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005108 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005109 Py_XDECREF(errorHandler);
5110 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005111 return NULL;
5112}
5113
Antoine Pitrouab868312009-01-10 15:40:25 +00005114#undef FAST_CHAR_MASK
5115#undef SWAPPED_FAST_CHAR_MASK
5116
Tim Peters772747b2001-08-09 22:21:55 +00005117PyObject *
5118PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005119 Py_ssize_t size,
5120 const char *errors,
5121 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005122{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005123 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005124 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005125 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005126#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005127 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005128#else
5129 const int pairs = 0;
5130#endif
Tim Peters772747b2001-08-09 22:21:55 +00005131 /* Offsets from p for storing byte pairs in the right order. */
5132#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5133 int ihi = 1, ilo = 0;
5134#else
5135 int ihi = 0, ilo = 1;
5136#endif
5137
Benjamin Peterson29060642009-01-31 22:14:21 +00005138#define STORECHAR(CH) \
5139 do { \
5140 p[ihi] = ((CH) >> 8) & 0xff; \
5141 p[ilo] = (CH) & 0xff; \
5142 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005143 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005144
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005145#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005146 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005147 if (s[i] >= 0x10000)
5148 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005149#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005150 /* 2 * (size + pairs + (byteorder == 0)) */
5151 if (size > PY_SSIZE_T_MAX ||
5152 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005153 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005154 nsize = size + pairs + (byteorder == 0);
5155 bytesize = nsize * 2;
5156 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005157 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005158 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005159 if (v == NULL)
5160 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005161
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005162 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005163 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005164 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005165 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005166 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005167
5168 if (byteorder == -1) {
5169 /* force LE */
5170 ihi = 1;
5171 ilo = 0;
5172 }
5173 else if (byteorder == 1) {
5174 /* force BE */
5175 ihi = 0;
5176 ilo = 1;
5177 }
5178
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005179 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 Py_UNICODE ch = *s++;
5181 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005182#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005183 if (ch >= 0x10000) {
5184 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5185 ch = 0xD800 | ((ch-0x10000) >> 10);
5186 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005187#endif
Tim Peters772747b2001-08-09 22:21:55 +00005188 STORECHAR(ch);
5189 if (ch2)
5190 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005191 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005192
5193 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005194 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005195#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196}
5197
Alexander Belopolsky40018472011-02-26 01:02:56 +00005198PyObject *
5199PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200{
5201 if (!PyUnicode_Check(unicode)) {
5202 PyErr_BadArgument();
5203 return NULL;
5204 }
5205 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 PyUnicode_GET_SIZE(unicode),
5207 NULL,
5208 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209}
5210
5211/* --- Unicode Escape Codec ----------------------------------------------- */
5212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005213/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5214 if all the escapes in the string make it still a valid ASCII string.
5215 Returns -1 if any escapes were found which cause the string to
5216 pop out of ASCII range. Otherwise returns the length of the
5217 required buffer to hold the string.
5218 */
5219Py_ssize_t
5220length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5221{
5222 const unsigned char *p = (const unsigned char *)s;
5223 const unsigned char *end = p + size;
5224 Py_ssize_t length = 0;
5225
5226 if (size < 0)
5227 return -1;
5228
5229 for (; p < end; ++p) {
5230 if (*p > 127) {
5231 /* Non-ASCII */
5232 return -1;
5233 }
5234 else if (*p != '\\') {
5235 /* Normal character */
5236 ++length;
5237 }
5238 else {
5239 /* Backslash-escape, check next char */
5240 ++p;
5241 /* Escape sequence reaches till end of string or
5242 non-ASCII follow-up. */
5243 if (p >= end || *p > 127)
5244 return -1;
5245 switch (*p) {
5246 case '\n':
5247 /* backslash + \n result in zero characters */
5248 break;
5249 case '\\': case '\'': case '\"':
5250 case 'b': case 'f': case 't':
5251 case 'n': case 'r': case 'v': case 'a':
5252 ++length;
5253 break;
5254 case '0': case '1': case '2': case '3':
5255 case '4': case '5': case '6': case '7':
5256 case 'x': case 'u': case 'U': case 'N':
5257 /* these do not guarantee ASCII characters */
5258 return -1;
5259 default:
5260 /* count the backslash + the other character */
5261 length += 2;
5262 }
5263 }
5264 }
5265 return length;
5266}
5267
5268/* Similar to PyUnicode_WRITE but either write into wstr field
5269 or treat string as ASCII. */
5270#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5271 do { \
5272 if ((kind) != PyUnicode_WCHAR_KIND) \
5273 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5274 else \
5275 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5276 } while (0)
5277
5278#define WRITE_WSTR(buf, index, value) \
5279 assert(kind == PyUnicode_WCHAR_KIND), \
5280 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5281
5282
Fredrik Lundh06d12682001-01-24 07:59:11 +00005283static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005284
Alexander Belopolsky40018472011-02-26 01:02:56 +00005285PyObject *
5286PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005287 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005288 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005289{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005290 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005291 Py_ssize_t startinpos;
5292 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005293 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005294 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005295 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005296 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005297 char* message;
5298 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005299 PyObject *errorHandler = NULL;
5300 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005301 Py_ssize_t ascii_length;
5302 Py_ssize_t i;
5303 int kind;
5304 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005306 ascii_length = length_of_escaped_ascii_string(s, size);
5307
5308 /* After length_of_escaped_ascii_string() there are two alternatives,
5309 either the string is pure ASCII with named escapes like \n, etc.
5310 and we determined it's exact size (common case)
5311 or it contains \x, \u, ... escape sequences. then we create a
5312 legacy wchar string and resize it at the end of this function. */
5313 if (ascii_length >= 0) {
5314 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5315 if (!v)
5316 goto onError;
5317 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5318 kind = PyUnicode_1BYTE_KIND;
5319 data = PyUnicode_DATA(v);
5320 }
5321 else {
5322 /* Escaped strings will always be longer than the resulting
5323 Unicode string, so we start with size here and then reduce the
5324 length after conversion to the true value.
5325 (but if the error callback returns a long replacement string
5326 we'll have to allocate more space) */
5327 v = _PyUnicode_New(size);
5328 if (!v)
5329 goto onError;
5330 kind = PyUnicode_WCHAR_KIND;
5331 data = PyUnicode_AS_UNICODE(v);
5332 }
5333
Guido van Rossumd57fd912000-03-10 22:53:23 +00005334 if (size == 0)
5335 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005336 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005338
Guido van Rossumd57fd912000-03-10 22:53:23 +00005339 while (s < end) {
5340 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005341 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005342 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005344 if (kind == PyUnicode_WCHAR_KIND) {
5345 assert(i < _PyUnicode_WSTR_LENGTH(v));
5346 }
5347 else {
5348 /* The only case in which i == ascii_length is a backslash
5349 followed by a newline. */
5350 assert(i <= ascii_length);
5351 }
5352
Guido van Rossumd57fd912000-03-10 22:53:23 +00005353 /* Non-escape characters are interpreted as Unicode ordinals */
5354 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005355 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005356 continue;
5357 }
5358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005359 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005360 /* \ - Escapes */
5361 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005362 c = *s++;
5363 if (s > end)
5364 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005365
5366 if (kind == PyUnicode_WCHAR_KIND) {
5367 assert(i < _PyUnicode_WSTR_LENGTH(v));
5368 }
5369 else {
5370 /* The only case in which i == ascii_length is a backslash
5371 followed by a newline. */
5372 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5373 }
5374
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005375 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005378 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005379 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5380 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5381 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5382 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5383 /* FF */
5384 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5385 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5386 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5387 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5388 /* VT */
5389 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5390 /* BEL, not classic C */
5391 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005392
Benjamin Peterson29060642009-01-31 22:14:21 +00005393 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005394 case '0': case '1': case '2': case '3':
5395 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005396 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005397 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005398 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005399 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005400 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005401 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005402 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005403 break;
5404
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 /* hex escapes */
5406 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005407 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005408 digits = 2;
5409 message = "truncated \\xXX escape";
5410 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005411
Benjamin Peterson29060642009-01-31 22:14:21 +00005412 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005414 digits = 4;
5415 message = "truncated \\uXXXX escape";
5416 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005419 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005420 digits = 8;
5421 message = "truncated \\UXXXXXXXX escape";
5422 hexescape:
5423 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005424 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005425 if (s+digits>end) {
5426 endinpos = size;
5427 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005428 errors, &errorHandler,
5429 "unicodeescape", "end of string in escape sequence",
5430 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005431 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005432 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005433 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 goto nextByte;
5435 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005436 for (j = 0; j < digits; ++j) {
5437 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005438 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005439 endinpos = (s+j+1)-starts;
5440 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005441 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005442 errors, &errorHandler,
5443 "unicodeescape", message,
5444 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005445 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005446 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005447 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005448 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005449 }
5450 chr = (chr<<4) & ~0xF;
5451 if (c >= '0' && c <= '9')
5452 chr += c - '0';
5453 else if (c >= 'a' && c <= 'f')
5454 chr += 10 + c - 'a';
5455 else
5456 chr += 10 + c - 'A';
5457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005458 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005459 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005460 /* _decoding_error will have already written into the
5461 target buffer. */
5462 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005463 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005464 /* when we get here, chr is a 32-bit unicode character */
5465 if (chr <= 0xffff)
5466 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005467 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005468 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005469 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005470 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005471#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005472 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005473#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005474 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005475 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5476 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005477#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005478 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005479 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005480 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005481 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005482 errors, &errorHandler,
5483 "unicodeescape", "illegal Unicode character",
5484 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005485 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005486 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005487 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005488 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005489 break;
5490
Benjamin Peterson29060642009-01-31 22:14:21 +00005491 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005492 case 'N':
5493 message = "malformed \\N character escape";
5494 if (ucnhash_CAPI == NULL) {
5495 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005496 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5497 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005498 if (ucnhash_CAPI == NULL)
5499 goto ucnhashError;
5500 }
5501 if (*s == '{') {
5502 const char *start = s+1;
5503 /* look for the closing brace */
5504 while (*s != '}' && s < end)
5505 s++;
5506 if (s > start && s < end && *s == '}') {
5507 /* found a name. look it up in the unicode database */
5508 message = "unknown Unicode character name";
5509 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005510 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5511 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005512 goto store;
5513 }
5514 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005515 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005516 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005517 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005518 errors, &errorHandler,
5519 "unicodeescape", message,
5520 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005521 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005522 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005523 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005524 break;
5525
5526 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005527 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005528 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005529 message = "\\ at end of string";
5530 s--;
5531 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005532 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005533 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005534 errors, &errorHandler,
5535 "unicodeescape", message,
5536 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005537 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005538 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005539 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005540 }
5541 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005542 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5543 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005544 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005545 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005547 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005548 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005550 /* Ensure the length prediction worked in case of ASCII strings */
5551 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5552
Victor Stinnerfe226c02011-10-03 03:52:20 +02005553 if (kind == PyUnicode_WCHAR_KIND)
5554 {
5555 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5556 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005557 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005558 Py_XDECREF(errorHandler);
5559 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005560 if (_PyUnicode_READY_REPLACE(&v)) {
5561 Py_DECREF(v);
5562 return NULL;
5563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005564 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005565
Benjamin Peterson29060642009-01-31 22:14:21 +00005566 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005567 PyErr_SetString(
5568 PyExc_UnicodeError,
5569 "\\N escapes not supported (can't load unicodedata module)"
5570 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005571 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005572 Py_XDECREF(errorHandler);
5573 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005574 return NULL;
5575
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005577 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005578 Py_XDECREF(errorHandler);
5579 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005580 return NULL;
5581}
5582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005583#undef WRITE_ASCII_OR_WSTR
5584#undef WRITE_WSTR
5585
Guido van Rossumd57fd912000-03-10 22:53:23 +00005586/* Return a Unicode-Escape string version of the Unicode object.
5587
5588 If quotes is true, the string is enclosed in u"" or u'' quotes as
5589 appropriate.
5590
5591*/
5592
Walter Dörwald79e913e2007-05-12 11:08:06 +00005593static const char *hexdigits = "0123456789abcdef";
5594
Alexander Belopolsky40018472011-02-26 01:02:56 +00005595PyObject *
5596PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005597 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005598{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005599 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005600 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005601
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005602#ifdef Py_UNICODE_WIDE
5603 const Py_ssize_t expandsize = 10;
5604#else
5605 const Py_ssize_t expandsize = 6;
5606#endif
5607
Thomas Wouters89f507f2006-12-13 04:49:30 +00005608 /* XXX(nnorwitz): rather than over-allocating, it would be
5609 better to choose a different scheme. Perhaps scan the
5610 first N-chars of the string and allocate based on that size.
5611 */
5612 /* Initial allocation is based on the longest-possible unichr
5613 escape.
5614
5615 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5616 unichr, so in this case it's the longest unichr escape. In
5617 narrow (UTF-16) builds this is five chars per source unichr
5618 since there are two unichrs in the surrogate pair, so in narrow
5619 (UTF-16) builds it's not the longest unichr escape.
5620
5621 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5622 so in the narrow (UTF-16) build case it's the longest unichr
5623 escape.
5624 */
5625
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005626 if (size == 0)
5627 return PyBytes_FromStringAndSize(NULL, 0);
5628
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005629 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005630 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005631
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005632 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005633 2
5634 + expandsize*size
5635 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 if (repr == NULL)
5637 return NULL;
5638
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005639 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005640
Guido van Rossumd57fd912000-03-10 22:53:23 +00005641 while (size-- > 0) {
5642 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005643
Walter Dörwald79e913e2007-05-12 11:08:06 +00005644 /* Escape backslashes */
5645 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005646 *p++ = '\\';
5647 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005648 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005649 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005650
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005651#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005652 /* Map 21-bit characters to '\U00xxxxxx' */
5653 else if (ch >= 0x10000) {
5654 *p++ = '\\';
5655 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005656 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5657 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5658 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5659 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5660 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5661 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5662 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5663 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005665 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005666#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005667 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5668 else if (ch >= 0xD800 && ch < 0xDC00) {
5669 Py_UNICODE ch2;
5670 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005671
Benjamin Peterson29060642009-01-31 22:14:21 +00005672 ch2 = *s++;
5673 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005674 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005675 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5676 *p++ = '\\';
5677 *p++ = 'U';
5678 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5679 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5680 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5681 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
5682 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
5683 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
5684 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
5685 *p++ = hexdigits[ucs & 0x0000000F];
5686 continue;
5687 }
5688 /* Fall through: isolated surrogates are copied as-is */
5689 s--;
5690 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005691 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005692#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005693
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005695 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 *p++ = '\\';
5697 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005698 *p++ = hexdigits[(ch >> 12) & 0x000F];
5699 *p++ = hexdigits[(ch >> 8) & 0x000F];
5700 *p++ = hexdigits[(ch >> 4) & 0x000F];
5701 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005703
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005704 /* Map special whitespace to '\t', \n', '\r' */
5705 else if (ch == '\t') {
5706 *p++ = '\\';
5707 *p++ = 't';
5708 }
5709 else if (ch == '\n') {
5710 *p++ = '\\';
5711 *p++ = 'n';
5712 }
5713 else if (ch == '\r') {
5714 *p++ = '\\';
5715 *p++ = 'r';
5716 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005717
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005718 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005719 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005720 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005721 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005722 *p++ = hexdigits[(ch >> 4) & 0x000F];
5723 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005724 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005725
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 /* Copy everything else as-is */
5727 else
5728 *p++ = (char) ch;
5729 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005731 assert(p - PyBytes_AS_STRING(repr) > 0);
5732 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5733 return NULL;
5734 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735}
5736
Alexander Belopolsky40018472011-02-26 01:02:56 +00005737PyObject *
5738PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005740 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741 if (!PyUnicode_Check(unicode)) {
5742 PyErr_BadArgument();
5743 return NULL;
5744 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005745 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5746 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005747 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005748}
5749
5750/* --- Raw Unicode Escape Codec ------------------------------------------- */
5751
Alexander Belopolsky40018472011-02-26 01:02:56 +00005752PyObject *
5753PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005754 Py_ssize_t size,
5755 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005757 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005758 Py_ssize_t startinpos;
5759 Py_ssize_t endinpos;
5760 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005762 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 const char *end;
5764 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 PyObject *errorHandler = NULL;
5766 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005767
Guido van Rossumd57fd912000-03-10 22:53:23 +00005768 /* Escaped strings will always be longer than the resulting
5769 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005770 length after conversion to the true value. (But decoding error
5771 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005772 v = _PyUnicode_New(size);
5773 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00005774 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005777 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778 end = s + size;
5779 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005780 unsigned char c;
5781 Py_UCS4 x;
5782 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005783 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784
Benjamin Peterson29060642009-01-31 22:14:21 +00005785 /* Non-escape characters are interpreted as Unicode ordinals */
5786 if (*s != '\\') {
5787 *p++ = (unsigned char)*s++;
5788 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005789 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005790 startinpos = s-starts;
5791
5792 /* \u-escapes are only interpreted iff the number of leading
5793 backslashes if odd */
5794 bs = s;
5795 for (;s < end;) {
5796 if (*s != '\\')
5797 break;
5798 *p++ = (unsigned char)*s++;
5799 }
5800 if (((s - bs) & 1) == 0 ||
5801 s >= end ||
5802 (*s != 'u' && *s != 'U')) {
5803 continue;
5804 }
5805 p--;
5806 count = *s=='u' ? 4 : 8;
5807 s++;
5808
5809 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
5810 outpos = p-PyUnicode_AS_UNICODE(v);
5811 for (x = 0, i = 0; i < count; ++i, ++s) {
5812 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00005813 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005814 endinpos = s-starts;
5815 if (unicode_decode_call_errorhandler(
5816 errors, &errorHandler,
5817 "rawunicodeescape", "truncated \\uXXXX",
5818 &starts, &end, &startinpos, &endinpos, &exc, &s,
5819 &v, &outpos, &p))
5820 goto onError;
5821 goto nextByte;
5822 }
5823 x = (x<<4) & ~0xF;
5824 if (c >= '0' && c <= '9')
5825 x += c - '0';
5826 else if (c >= 'a' && c <= 'f')
5827 x += 10 + c - 'a';
5828 else
5829 x += 10 + c - 'A';
5830 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00005831 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00005832 /* UCS-2 character */
5833 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005834 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005835 /* UCS-4 character. Either store directly, or as
5836 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00005837#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005838 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005839#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005840 x -= 0x10000L;
5841 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
5842 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00005843#endif
5844 } else {
5845 endinpos = s-starts;
5846 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005847 if (unicode_decode_call_errorhandler(
5848 errors, &errorHandler,
5849 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00005850 &starts, &end, &startinpos, &endinpos, &exc, &s,
5851 &v, &outpos, &p))
5852 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005853 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 nextByte:
5855 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02005857 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005858 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 Py_XDECREF(errorHandler);
5860 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005861 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005862 Py_DECREF(v);
5863 return NULL;
5864 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00005866
Benjamin Peterson29060642009-01-31 22:14:21 +00005867 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 Py_XDECREF(errorHandler);
5870 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 return NULL;
5872}
5873
Alexander Belopolsky40018472011-02-26 01:02:56 +00005874PyObject *
5875PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005876 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005878 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 char *p;
5880 char *q;
5881
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005882#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005883 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005884#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005885 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005886#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00005887
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005888 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005889 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00005890
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005891 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 if (repr == NULL)
5893 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00005894 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005895 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005896
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005897 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 while (size-- > 0) {
5899 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005900#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005901 /* Map 32-bit characters to '\Uxxxxxxxx' */
5902 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005903 *p++ = '\\';
5904 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005905 *p++ = hexdigits[(ch >> 28) & 0xf];
5906 *p++ = hexdigits[(ch >> 24) & 0xf];
5907 *p++ = hexdigits[(ch >> 20) & 0xf];
5908 *p++ = hexdigits[(ch >> 16) & 0xf];
5909 *p++ = hexdigits[(ch >> 12) & 0xf];
5910 *p++ = hexdigits[(ch >> 8) & 0xf];
5911 *p++ = hexdigits[(ch >> 4) & 0xf];
5912 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00005913 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005914 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00005915#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5917 if (ch >= 0xD800 && ch < 0xDC00) {
5918 Py_UNICODE ch2;
5919 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00005920
Benjamin Peterson29060642009-01-31 22:14:21 +00005921 ch2 = *s++;
5922 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005923 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005924 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5925 *p++ = '\\';
5926 *p++ = 'U';
5927 *p++ = hexdigits[(ucs >> 28) & 0xf];
5928 *p++ = hexdigits[(ucs >> 24) & 0xf];
5929 *p++ = hexdigits[(ucs >> 20) & 0xf];
5930 *p++ = hexdigits[(ucs >> 16) & 0xf];
5931 *p++ = hexdigits[(ucs >> 12) & 0xf];
5932 *p++ = hexdigits[(ucs >> 8) & 0xf];
5933 *p++ = hexdigits[(ucs >> 4) & 0xf];
5934 *p++ = hexdigits[ucs & 0xf];
5935 continue;
5936 }
5937 /* Fall through: isolated surrogates are copied as-is */
5938 s--;
5939 size++;
5940 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00005941#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005942 /* Map 16-bit characters to '\uxxxx' */
5943 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944 *p++ = '\\';
5945 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00005946 *p++ = hexdigits[(ch >> 12) & 0xf];
5947 *p++ = hexdigits[(ch >> 8) & 0xf];
5948 *p++ = hexdigits[(ch >> 4) & 0xf];
5949 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 /* Copy everything else as-is */
5952 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00005953 *p++ = (char) ch;
5954 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005955 size = p - q;
5956
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 assert(size > 0);
5958 if (_PyBytes_Resize(&repr, size) < 0)
5959 return NULL;
5960 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005961}
5962
Alexander Belopolsky40018472011-02-26 01:02:56 +00005963PyObject *
5964PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005965{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005966 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00005968 PyErr_BadArgument();
5969 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970 }
Walter Dörwald711005d2007-05-12 12:03:26 +00005971 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5972 PyUnicode_GET_SIZE(unicode));
5973
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005974 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975}
5976
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005977/* --- Unicode Internal Codec ------------------------------------------- */
5978
Alexander Belopolsky40018472011-02-26 01:02:56 +00005979PyObject *
5980_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005981 Py_ssize_t size,
5982 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005983{
5984 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005985 Py_ssize_t startinpos;
5986 Py_ssize_t endinpos;
5987 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00005988 PyUnicodeObject *v;
5989 Py_UNICODE *p;
5990 const char *end;
5991 const char *reason;
5992 PyObject *errorHandler = NULL;
5993 PyObject *exc = NULL;
5994
Neal Norwitzd43069c2006-01-08 01:12:10 +00005995#ifdef Py_UNICODE_WIDE
5996 Py_UNICODE unimax = PyUnicode_GetMax();
5997#endif
5998
Thomas Wouters89f507f2006-12-13 04:49:30 +00005999 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006000 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6001 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006003 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6004 as string was created with the old API. */
6005 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006006 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006007 p = PyUnicode_AS_UNICODE(v);
6008 end = s + size;
6009
6010 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006011 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006012 /* We have to sanity check the raw data, otherwise doom looms for
6013 some malformed UCS-4 data. */
6014 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006015#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006016 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006017#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006018 end-s < Py_UNICODE_SIZE
6019 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006020 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006021 startinpos = s - starts;
6022 if (end-s < Py_UNICODE_SIZE) {
6023 endinpos = end-starts;
6024 reason = "truncated input";
6025 }
6026 else {
6027 endinpos = s - starts + Py_UNICODE_SIZE;
6028 reason = "illegal code point (> 0x10FFFF)";
6029 }
6030 outpos = p - PyUnicode_AS_UNICODE(v);
6031 if (unicode_decode_call_errorhandler(
6032 errors, &errorHandler,
6033 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006034 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006035 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006036 goto onError;
6037 }
6038 }
6039 else {
6040 p++;
6041 s += Py_UNICODE_SIZE;
6042 }
6043 }
6044
Victor Stinnerfe226c02011-10-03 03:52:20 +02006045 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006046 goto onError;
6047 Py_XDECREF(errorHandler);
6048 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006049 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006050 Py_DECREF(v);
6051 return NULL;
6052 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006053 return (PyObject *)v;
6054
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006056 Py_XDECREF(v);
6057 Py_XDECREF(errorHandler);
6058 Py_XDECREF(exc);
6059 return NULL;
6060}
6061
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062/* --- Latin-1 Codec ------------------------------------------------------ */
6063
Alexander Belopolsky40018472011-02-26 01:02:56 +00006064PyObject *
6065PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006066 Py_ssize_t size,
6067 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006069 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006070 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071}
6072
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006073/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006074static void
6075make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006076 const char *encoding,
6077 const Py_UNICODE *unicode, Py_ssize_t size,
6078 Py_ssize_t startpos, Py_ssize_t endpos,
6079 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006081 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 *exceptionObject = PyUnicodeEncodeError_Create(
6083 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 }
6085 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6087 goto onError;
6088 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6089 goto onError;
6090 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6091 goto onError;
6092 return;
6093 onError:
6094 Py_DECREF(*exceptionObject);
6095 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096 }
6097}
6098
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006100static void
6101raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006102 const char *encoding,
6103 const Py_UNICODE *unicode, Py_ssize_t size,
6104 Py_ssize_t startpos, Py_ssize_t endpos,
6105 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006106{
6107 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006109 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006110 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006111}
6112
6113/* error handling callback helper:
6114 build arguments, call the callback and check the arguments,
6115 put the result into newpos and return the replacement string, which
6116 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006117static PyObject *
6118unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006119 PyObject **errorHandler,
6120 const char *encoding, const char *reason,
6121 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6122 Py_ssize_t startpos, Py_ssize_t endpos,
6123 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006124{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006125 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006126
6127 PyObject *restuple;
6128 PyObject *resunicode;
6129
6130 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006131 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006132 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006133 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006134 }
6135
6136 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006137 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006138 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006139 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006140
6141 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006142 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006143 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006145 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006146 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 Py_DECREF(restuple);
6148 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006149 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006150 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 &resunicode, newpos)) {
6152 Py_DECREF(restuple);
6153 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006154 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006155 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6156 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6157 Py_DECREF(restuple);
6158 return NULL;
6159 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006160 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006161 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006162 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006163 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6164 Py_DECREF(restuple);
6165 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006166 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006167 Py_INCREF(resunicode);
6168 Py_DECREF(restuple);
6169 return resunicode;
6170}
6171
Alexander Belopolsky40018472011-02-26 01:02:56 +00006172static PyObject *
6173unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006174 Py_ssize_t size,
6175 const char *errors,
6176 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006177{
6178 /* output object */
6179 PyObject *res;
6180 /* pointers to the beginning and end+1 of input */
6181 const Py_UNICODE *startp = p;
6182 const Py_UNICODE *endp = p + size;
6183 /* pointer to the beginning of the unencodable characters */
6184 /* const Py_UNICODE *badp = NULL; */
6185 /* pointer into the output */
6186 char *str;
6187 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006188 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006189 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6190 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006191 PyObject *errorHandler = NULL;
6192 PyObject *exc = NULL;
6193 /* the following variable is used for caching string comparisons
6194 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6195 int known_errorHandler = -1;
6196
6197 /* allocate enough for a simple encoding without
6198 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006199 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006200 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006201 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006202 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006203 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006204 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006205 ressize = size;
6206
6207 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006208 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006209
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 /* can we encode this? */
6211 if (c<limit) {
6212 /* no overflow check, because we know that the space is enough */
6213 *str++ = (char)c;
6214 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006215 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 else {
6217 Py_ssize_t unicodepos = p-startp;
6218 Py_ssize_t requiredsize;
6219 PyObject *repunicode;
6220 Py_ssize_t repsize;
6221 Py_ssize_t newpos;
6222 Py_ssize_t respos;
6223 Py_UNICODE *uni2;
6224 /* startpos for collecting unencodable chars */
6225 const Py_UNICODE *collstart = p;
6226 const Py_UNICODE *collend = p;
6227 /* find all unecodable characters */
6228 while ((collend < endp) && ((*collend)>=limit))
6229 ++collend;
6230 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6231 if (known_errorHandler==-1) {
6232 if ((errors==NULL) || (!strcmp(errors, "strict")))
6233 known_errorHandler = 1;
6234 else if (!strcmp(errors, "replace"))
6235 known_errorHandler = 2;
6236 else if (!strcmp(errors, "ignore"))
6237 known_errorHandler = 3;
6238 else if (!strcmp(errors, "xmlcharrefreplace"))
6239 known_errorHandler = 4;
6240 else
6241 known_errorHandler = 0;
6242 }
6243 switch (known_errorHandler) {
6244 case 1: /* strict */
6245 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6246 goto onError;
6247 case 2: /* replace */
6248 while (collstart++<collend)
6249 *str++ = '?'; /* fall through */
6250 case 3: /* ignore */
6251 p = collend;
6252 break;
6253 case 4: /* xmlcharrefreplace */
6254 respos = str - PyBytes_AS_STRING(res);
6255 /* determine replacement size (temporarily (mis)uses p) */
6256 for (p = collstart, repsize = 0; p < collend; ++p) {
6257 if (*p<10)
6258 repsize += 2+1+1;
6259 else if (*p<100)
6260 repsize += 2+2+1;
6261 else if (*p<1000)
6262 repsize += 2+3+1;
6263 else if (*p<10000)
6264 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006265#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006266 else
6267 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006268#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 else if (*p<100000)
6270 repsize += 2+5+1;
6271 else if (*p<1000000)
6272 repsize += 2+6+1;
6273 else
6274 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006275#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 }
6277 requiredsize = respos+repsize+(endp-collend);
6278 if (requiredsize > ressize) {
6279 if (requiredsize<2*ressize)
6280 requiredsize = 2*ressize;
6281 if (_PyBytes_Resize(&res, requiredsize))
6282 goto onError;
6283 str = PyBytes_AS_STRING(res) + respos;
6284 ressize = requiredsize;
6285 }
6286 /* generate replacement (temporarily (mis)uses p) */
6287 for (p = collstart; p < collend; ++p) {
6288 str += sprintf(str, "&#%d;", (int)*p);
6289 }
6290 p = collend;
6291 break;
6292 default:
6293 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6294 encoding, reason, startp, size, &exc,
6295 collstart-startp, collend-startp, &newpos);
6296 if (repunicode == NULL)
6297 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006298 if (PyBytes_Check(repunicode)) {
6299 /* Directly copy bytes result to output. */
6300 repsize = PyBytes_Size(repunicode);
6301 if (repsize > 1) {
6302 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006303 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006304 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6305 Py_DECREF(repunicode);
6306 goto onError;
6307 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006308 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006309 ressize += repsize-1;
6310 }
6311 memcpy(str, PyBytes_AsString(repunicode), repsize);
6312 str += repsize;
6313 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006314 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006315 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 /* need more space? (at least enough for what we
6318 have+the replacement+the rest of the string, so
6319 we won't have to check space for encodable characters) */
6320 respos = str - PyBytes_AS_STRING(res);
6321 repsize = PyUnicode_GET_SIZE(repunicode);
6322 requiredsize = respos+repsize+(endp-collend);
6323 if (requiredsize > ressize) {
6324 if (requiredsize<2*ressize)
6325 requiredsize = 2*ressize;
6326 if (_PyBytes_Resize(&res, requiredsize)) {
6327 Py_DECREF(repunicode);
6328 goto onError;
6329 }
6330 str = PyBytes_AS_STRING(res) + respos;
6331 ressize = requiredsize;
6332 }
6333 /* check if there is anything unencodable in the replacement
6334 and copy it to the output */
6335 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6336 c = *uni2;
6337 if (c >= limit) {
6338 raise_encode_exception(&exc, encoding, startp, size,
6339 unicodepos, unicodepos+1, reason);
6340 Py_DECREF(repunicode);
6341 goto onError;
6342 }
6343 *str = (char)c;
6344 }
6345 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006346 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006347 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006348 }
6349 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006350 /* Resize if we allocated to much */
6351 size = str - PyBytes_AS_STRING(res);
6352 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006353 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006354 if (_PyBytes_Resize(&res, size) < 0)
6355 goto onError;
6356 }
6357
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358 Py_XDECREF(errorHandler);
6359 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006360 return res;
6361
6362 onError:
6363 Py_XDECREF(res);
6364 Py_XDECREF(errorHandler);
6365 Py_XDECREF(exc);
6366 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367}
6368
Alexander Belopolsky40018472011-02-26 01:02:56 +00006369PyObject *
6370PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006371 Py_ssize_t size,
6372 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006373{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006374 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375}
6376
Alexander Belopolsky40018472011-02-26 01:02:56 +00006377PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006378_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379{
6380 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 PyErr_BadArgument();
6382 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006383 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006384 if (PyUnicode_READY(unicode) == -1)
6385 return NULL;
6386 /* Fast path: if it is a one-byte string, construct
6387 bytes object directly. */
6388 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6389 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6390 PyUnicode_GET_LENGTH(unicode));
6391 /* Non-Latin-1 characters present. Defer to above function to
6392 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006394 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006395 errors);
6396}
6397
6398PyObject*
6399PyUnicode_AsLatin1String(PyObject *unicode)
6400{
6401 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006402}
6403
6404/* --- 7-bit ASCII Codec -------------------------------------------------- */
6405
Alexander Belopolsky40018472011-02-26 01:02:56 +00006406PyObject *
6407PyUnicode_DecodeASCII(const char *s,
6408 Py_ssize_t size,
6409 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006410{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412 PyUnicodeObject *v;
6413 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006414 Py_ssize_t startinpos;
6415 Py_ssize_t endinpos;
6416 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 const char *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006418 unsigned char* d;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 PyObject *errorHandler = NULL;
6420 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006421 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00006422
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006424 if (size == 1 && *(unsigned char*)s < 128)
6425 return PyUnicode_FromOrdinal(*(unsigned char*)s);
6426
6427 /* Fast path. Assume the input actually *is* ASCII, and allocate
6428 a single-block Unicode object with that assumption. If there is
6429 an error, drop the object and start over. */
6430 v = (PyUnicodeObject*)PyUnicode_New(size, 127);
6431 if (v == NULL)
6432 goto onError;
6433 d = PyUnicode_1BYTE_DATA(v);
6434 for (i = 0; i < size; i++) {
6435 unsigned char ch = ((unsigned char*)s)[i];
6436 if (ch < 128)
6437 d[i] = ch;
6438 else
6439 break;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006441 if (i == size)
6442 return (PyObject*)v;
6443 Py_DECREF(v); /* start over */
Tim Petersced69f82003-09-16 20:30:58 +00006444
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445 v = _PyUnicode_New(size);
6446 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006447 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006448 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006449 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006451 e = s + size;
6452 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 register unsigned char c = (unsigned char)*s;
6454 if (c < 128) {
6455 *p++ = c;
6456 ++s;
6457 }
6458 else {
6459 startinpos = s-starts;
6460 endinpos = startinpos + 1;
6461 outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
6462 if (unicode_decode_call_errorhandler(
6463 errors, &errorHandler,
6464 "ascii", "ordinal not in range(128)",
6465 &starts, &e, &startinpos, &endinpos, &exc, &s,
6466 &v, &outpos, &p))
6467 goto onError;
6468 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006469 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00006470 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006471 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006473 Py_XDECREF(errorHandler);
6474 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006475 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006476 Py_DECREF(v);
6477 return NULL;
6478 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006480
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006482 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 Py_XDECREF(errorHandler);
6484 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485 return NULL;
6486}
6487
Alexander Belopolsky40018472011-02-26 01:02:56 +00006488PyObject *
6489PyUnicode_EncodeASCII(const Py_UNICODE *p,
6490 Py_ssize_t size,
6491 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006492{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494}
6495
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006497_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006498{
6499 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 PyErr_BadArgument();
6501 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006503 if (PyUnicode_READY(unicode) == -1)
6504 return NULL;
6505 /* Fast path: if it is an ASCII-only string, construct bytes object
6506 directly. Else defer to above function to raise the exception. */
6507 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6508 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6509 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006512 errors);
6513}
6514
6515PyObject *
6516PyUnicode_AsASCIIString(PyObject *unicode)
6517{
6518 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519}
6520
Victor Stinner99b95382011-07-04 14:23:54 +02006521#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006522
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006523/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006524
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006525#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006526#define NEED_RETRY
6527#endif
6528
6529/* XXX This code is limited to "true" double-byte encodings, as
6530 a) it assumes an incomplete character consists of a single byte, and
6531 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006533
Alexander Belopolsky40018472011-02-26 01:02:56 +00006534static int
6535is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006536{
6537 const char *curr = s + offset;
6538
6539 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 const char *prev = CharPrev(s, curr);
6541 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006542 }
6543 return 0;
6544}
6545
6546/*
6547 * Decode MBCS string into unicode object. If 'final' is set, converts
6548 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6549 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006550static int
6551decode_mbcs(PyUnicodeObject **v,
6552 const char *s, /* MBCS string */
6553 int size, /* sizeof MBCS string */
6554 int final,
6555 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006556{
6557 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006558 Py_ssize_t n;
6559 DWORD usize;
6560 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006561
6562 assert(size >= 0);
6563
Victor Stinner554f3f02010-06-16 23:33:54 +00006564 /* check and handle 'errors' arg */
6565 if (errors==NULL || strcmp(errors, "strict")==0)
6566 flags = MB_ERR_INVALID_CHARS;
6567 else if (strcmp(errors, "ignore")==0)
6568 flags = 0;
6569 else {
6570 PyErr_Format(PyExc_ValueError,
6571 "mbcs encoding does not support errors='%s'",
6572 errors);
6573 return -1;
6574 }
6575
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006576 /* Skip trailing lead-byte unless 'final' is set */
6577 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006579
6580 /* First get the size of the result */
6581 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006582 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6583 if (usize==0)
6584 goto mbcs_decode_error;
6585 } else
6586 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006587
6588 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 /* Create unicode object */
6590 *v = _PyUnicode_New(usize);
6591 if (*v == NULL)
6592 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006593 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006594 }
6595 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 /* Extend unicode object */
6597 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006598 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006600 }
6601
6602 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006603 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006605 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6606 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006608 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006609 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006610
6611mbcs_decode_error:
6612 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6613 we raise a UnicodeDecodeError - else it is a 'generic'
6614 windows error
6615 */
6616 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6617 /* Ideally, we should get reason from FormatMessage - this
6618 is the Windows 2000 English version of the message
6619 */
6620 PyObject *exc = NULL;
6621 const char *reason = "No mapping for the Unicode character exists "
6622 "in the target multi-byte code page.";
6623 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6624 if (exc != NULL) {
6625 PyCodec_StrictErrors(exc);
6626 Py_DECREF(exc);
6627 }
6628 } else {
6629 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6630 }
6631 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006632}
6633
Alexander Belopolsky40018472011-02-26 01:02:56 +00006634PyObject *
6635PyUnicode_DecodeMBCSStateful(const char *s,
6636 Py_ssize_t size,
6637 const char *errors,
6638 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006639{
6640 PyUnicodeObject *v = NULL;
6641 int done;
6642
6643 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006644 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006645
6646#ifdef NEED_RETRY
6647 retry:
6648 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006649 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006650 else
6651#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006652 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006653
6654 if (done < 0) {
6655 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006657 }
6658
6659 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006661
6662#ifdef NEED_RETRY
6663 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 s += done;
6665 size -= done;
6666 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006667 }
6668#endif
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006669 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006670 Py_DECREF(v);
6671 return NULL;
6672 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006673 return (PyObject *)v;
6674}
6675
Alexander Belopolsky40018472011-02-26 01:02:56 +00006676PyObject *
6677PyUnicode_DecodeMBCS(const char *s,
6678 Py_ssize_t size,
6679 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006680{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006681 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
6682}
6683
6684/*
6685 * Convert unicode into string object (MBCS).
6686 * Returns 0 if succeed, -1 otherwise.
6687 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006688static int
6689encode_mbcs(PyObject **repr,
6690 const Py_UNICODE *p, /* unicode */
6691 int size, /* size of unicode */
6692 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006693{
Victor Stinner554f3f02010-06-16 23:33:54 +00006694 BOOL usedDefaultChar = FALSE;
6695 BOOL *pusedDefaultChar;
6696 int mbcssize;
6697 Py_ssize_t n;
6698 PyObject *exc = NULL;
6699 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006700
6701 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006702
Victor Stinner554f3f02010-06-16 23:33:54 +00006703 /* check and handle 'errors' arg */
6704 if (errors==NULL || strcmp(errors, "strict")==0) {
6705 flags = WC_NO_BEST_FIT_CHARS;
6706 pusedDefaultChar = &usedDefaultChar;
6707 } else if (strcmp(errors, "replace")==0) {
6708 flags = 0;
6709 pusedDefaultChar = NULL;
6710 } else {
6711 PyErr_Format(PyExc_ValueError,
6712 "mbcs encoding does not support errors='%s'",
6713 errors);
6714 return -1;
6715 }
6716
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006717 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006718 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006719 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
6720 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 if (mbcssize == 0) {
6722 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6723 return -1;
6724 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006725 /* If we used a default char, then we failed! */
6726 if (pusedDefaultChar && *pusedDefaultChar)
6727 goto mbcs_encode_error;
6728 } else {
6729 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006730 }
6731
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006732 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 /* Create string object */
6734 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
6735 if (*repr == NULL)
6736 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006737 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006738 }
6739 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 /* Extend string object */
6741 n = PyBytes_Size(*repr);
6742 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
6743 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006744 }
6745
6746 /* Do the conversion */
6747 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006749 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
6750 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6752 return -1;
6753 }
Victor Stinner554f3f02010-06-16 23:33:54 +00006754 if (pusedDefaultChar && *pusedDefaultChar)
6755 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006756 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006757 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00006758
6759mbcs_encode_error:
6760 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
6761 Py_XDECREF(exc);
6762 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006763}
6764
Alexander Belopolsky40018472011-02-26 01:02:56 +00006765PyObject *
6766PyUnicode_EncodeMBCS(const Py_UNICODE *p,
6767 Py_ssize_t size,
6768 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006769{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006770 PyObject *repr = NULL;
6771 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00006772
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006773#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006775 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006776 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006777 else
6778#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006779 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006780
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006781 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 Py_XDECREF(repr);
6783 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006784 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006785
6786#ifdef NEED_RETRY
6787 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 p += INT_MAX;
6789 size -= INT_MAX;
6790 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006791 }
6792#endif
6793
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006794 return repr;
6795}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006796
Alexander Belopolsky40018472011-02-26 01:02:56 +00006797PyObject *
6798PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006799{
6800 if (!PyUnicode_Check(unicode)) {
6801 PyErr_BadArgument();
6802 return NULL;
6803 }
6804 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006805 PyUnicode_GET_SIZE(unicode),
6806 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00006807}
6808
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809#undef NEED_RETRY
6810
Victor Stinner99b95382011-07-04 14:23:54 +02006811#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006812
Guido van Rossumd57fd912000-03-10 22:53:23 +00006813/* --- Character Mapping Codec -------------------------------------------- */
6814
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
6816PyUnicode_DecodeCharmap(const char *s,
6817 Py_ssize_t size,
6818 PyObject *mapping,
6819 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006821 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006822 Py_ssize_t startinpos;
6823 Py_ssize_t endinpos;
6824 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006825 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006826 PyUnicodeObject *v;
6827 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006828 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006829 PyObject *errorHandler = NULL;
6830 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006831 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006832 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00006833
Guido van Rossumd57fd912000-03-10 22:53:23 +00006834 /* Default to Latin-1 */
6835 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006836 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006837
6838 v = _PyUnicode_New(size);
6839 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006840 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006843 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006844 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006845 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006846 mapstring = PyUnicode_AS_UNICODE(mapping);
6847 maplen = PyUnicode_GET_SIZE(mapping);
6848 while (s < e) {
6849 unsigned char ch = *s;
6850 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006851
Benjamin Peterson29060642009-01-31 22:14:21 +00006852 if (ch < maplen)
6853 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854
Benjamin Peterson29060642009-01-31 22:14:21 +00006855 if (x == 0xfffe) {
6856 /* undefined mapping */
6857 outpos = p-PyUnicode_AS_UNICODE(v);
6858 startinpos = s-starts;
6859 endinpos = startinpos+1;
6860 if (unicode_decode_call_errorhandler(
6861 errors, &errorHandler,
6862 "charmap", "character maps to <undefined>",
6863 &starts, &e, &startinpos, &endinpos, &exc, &s,
6864 &v, &outpos, &p)) {
6865 goto onError;
6866 }
6867 continue;
6868 }
6869 *p++ = x;
6870 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006871 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006872 }
6873 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006874 while (s < e) {
6875 unsigned char ch = *s;
6876 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00006877
Benjamin Peterson29060642009-01-31 22:14:21 +00006878 /* Get mapping (char ordinal -> integer, Unicode char or None) */
6879 w = PyLong_FromLong((long)ch);
6880 if (w == NULL)
6881 goto onError;
6882 x = PyObject_GetItem(mapping, w);
6883 Py_DECREF(w);
6884 if (x == NULL) {
6885 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
6886 /* No mapping found means: mapping is undefined. */
6887 PyErr_Clear();
6888 x = Py_None;
6889 Py_INCREF(x);
6890 } else
6891 goto onError;
6892 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006893
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 /* Apply mapping */
6895 if (PyLong_Check(x)) {
6896 long value = PyLong_AS_LONG(x);
6897 if (value < 0 || value > 65535) {
6898 PyErr_SetString(PyExc_TypeError,
6899 "character mapping must be in range(65536)");
6900 Py_DECREF(x);
6901 goto onError;
6902 }
6903 *p++ = (Py_UNICODE)value;
6904 }
6905 else if (x == Py_None) {
6906 /* undefined mapping */
6907 outpos = p-PyUnicode_AS_UNICODE(v);
6908 startinpos = s-starts;
6909 endinpos = startinpos+1;
6910 if (unicode_decode_call_errorhandler(
6911 errors, &errorHandler,
6912 "charmap", "character maps to <undefined>",
6913 &starts, &e, &startinpos, &endinpos, &exc, &s,
6914 &v, &outpos, &p)) {
6915 Py_DECREF(x);
6916 goto onError;
6917 }
6918 Py_DECREF(x);
6919 continue;
6920 }
6921 else if (PyUnicode_Check(x)) {
6922 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006923
Benjamin Peterson29060642009-01-31 22:14:21 +00006924 if (targetsize == 1)
6925 /* 1-1 mapping */
6926 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006927
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 else if (targetsize > 1) {
6929 /* 1-n mapping */
6930 if (targetsize > extrachars) {
6931 /* resize first */
6932 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
6933 Py_ssize_t needed = (targetsize - extrachars) + \
6934 (targetsize << 2);
6935 extrachars += needed;
6936 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02006937 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 PyUnicode_GET_SIZE(v) + needed) < 0) {
6939 Py_DECREF(x);
6940 goto onError;
6941 }
6942 p = PyUnicode_AS_UNICODE(v) + oldpos;
6943 }
6944 Py_UNICODE_COPY(p,
6945 PyUnicode_AS_UNICODE(x),
6946 targetsize);
6947 p += targetsize;
6948 extrachars -= targetsize;
6949 }
6950 /* 1-0 mapping: skip the character */
6951 }
6952 else {
6953 /* wrong return value */
6954 PyErr_SetString(PyExc_TypeError,
6955 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00006956 Py_DECREF(x);
6957 goto onError;
6958 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 Py_DECREF(x);
6960 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006961 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006962 }
6963 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02006964 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006966 Py_XDECREF(errorHandler);
6967 Py_XDECREF(exc);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006968 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006969 Py_DECREF(v);
6970 return NULL;
6971 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006973
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006975 Py_XDECREF(errorHandler);
6976 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006977 Py_XDECREF(v);
6978 return NULL;
6979}
6980
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006981/* Charmap encoding: the lookup table */
6982
Alexander Belopolsky40018472011-02-26 01:02:56 +00006983struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 PyObject_HEAD
6985 unsigned char level1[32];
6986 int count2, count3;
6987 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006988};
6989
6990static PyObject*
6991encoding_map_size(PyObject *obj, PyObject* args)
6992{
6993 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006994 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00006995 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006996}
6997
6998static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00006999 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007000 PyDoc_STR("Return the size (in bytes) of this object") },
7001 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007002};
7003
7004static void
7005encoding_map_dealloc(PyObject* o)
7006{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007007 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007008}
7009
7010static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007011 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007012 "EncodingMap", /*tp_name*/
7013 sizeof(struct encoding_map), /*tp_basicsize*/
7014 0, /*tp_itemsize*/
7015 /* methods */
7016 encoding_map_dealloc, /*tp_dealloc*/
7017 0, /*tp_print*/
7018 0, /*tp_getattr*/
7019 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007020 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007021 0, /*tp_repr*/
7022 0, /*tp_as_number*/
7023 0, /*tp_as_sequence*/
7024 0, /*tp_as_mapping*/
7025 0, /*tp_hash*/
7026 0, /*tp_call*/
7027 0, /*tp_str*/
7028 0, /*tp_getattro*/
7029 0, /*tp_setattro*/
7030 0, /*tp_as_buffer*/
7031 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7032 0, /*tp_doc*/
7033 0, /*tp_traverse*/
7034 0, /*tp_clear*/
7035 0, /*tp_richcompare*/
7036 0, /*tp_weaklistoffset*/
7037 0, /*tp_iter*/
7038 0, /*tp_iternext*/
7039 encoding_map_methods, /*tp_methods*/
7040 0, /*tp_members*/
7041 0, /*tp_getset*/
7042 0, /*tp_base*/
7043 0, /*tp_dict*/
7044 0, /*tp_descr_get*/
7045 0, /*tp_descr_set*/
7046 0, /*tp_dictoffset*/
7047 0, /*tp_init*/
7048 0, /*tp_alloc*/
7049 0, /*tp_new*/
7050 0, /*tp_free*/
7051 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007052};
7053
7054PyObject*
7055PyUnicode_BuildEncodingMap(PyObject* string)
7056{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007057 PyObject *result;
7058 struct encoding_map *mresult;
7059 int i;
7060 int need_dict = 0;
7061 unsigned char level1[32];
7062 unsigned char level2[512];
7063 unsigned char *mlevel1, *mlevel2, *mlevel3;
7064 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007065 int kind;
7066 void *data;
7067 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007069 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007070 PyErr_BadArgument();
7071 return NULL;
7072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007073 kind = PyUnicode_KIND(string);
7074 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007075 memset(level1, 0xFF, sizeof level1);
7076 memset(level2, 0xFF, sizeof level2);
7077
7078 /* If there isn't a one-to-one mapping of NULL to \0,
7079 or if there are non-BMP characters, we need to use
7080 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007081 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007082 need_dict = 1;
7083 for (i = 1; i < 256; i++) {
7084 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007085 ch = PyUnicode_READ(kind, data, i);
7086 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007087 need_dict = 1;
7088 break;
7089 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007090 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007091 /* unmapped character */
7092 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007093 l1 = ch >> 11;
7094 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007095 if (level1[l1] == 0xFF)
7096 level1[l1] = count2++;
7097 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007098 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007099 }
7100
7101 if (count2 >= 0xFF || count3 >= 0xFF)
7102 need_dict = 1;
7103
7104 if (need_dict) {
7105 PyObject *result = PyDict_New();
7106 PyObject *key, *value;
7107 if (!result)
7108 return NULL;
7109 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007110 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007111 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007112 if (!key || !value)
7113 goto failed1;
7114 if (PyDict_SetItem(result, key, value) == -1)
7115 goto failed1;
7116 Py_DECREF(key);
7117 Py_DECREF(value);
7118 }
7119 return result;
7120 failed1:
7121 Py_XDECREF(key);
7122 Py_XDECREF(value);
7123 Py_DECREF(result);
7124 return NULL;
7125 }
7126
7127 /* Create a three-level trie */
7128 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7129 16*count2 + 128*count3 - 1);
7130 if (!result)
7131 return PyErr_NoMemory();
7132 PyObject_Init(result, &EncodingMapType);
7133 mresult = (struct encoding_map*)result;
7134 mresult->count2 = count2;
7135 mresult->count3 = count3;
7136 mlevel1 = mresult->level1;
7137 mlevel2 = mresult->level23;
7138 mlevel3 = mresult->level23 + 16*count2;
7139 memcpy(mlevel1, level1, 32);
7140 memset(mlevel2, 0xFF, 16*count2);
7141 memset(mlevel3, 0, 128*count3);
7142 count3 = 0;
7143 for (i = 1; i < 256; i++) {
7144 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007145 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007146 /* unmapped character */
7147 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007148 o1 = PyUnicode_READ(kind, data, i)>>11;
7149 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007150 i2 = 16*mlevel1[o1] + o2;
7151 if (mlevel2[i2] == 0xFF)
7152 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007153 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007154 i3 = 128*mlevel2[i2] + o3;
7155 mlevel3[i3] = i;
7156 }
7157 return result;
7158}
7159
7160static int
7161encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7162{
7163 struct encoding_map *map = (struct encoding_map*)mapping;
7164 int l1 = c>>11;
7165 int l2 = (c>>7) & 0xF;
7166 int l3 = c & 0x7F;
7167 int i;
7168
7169#ifdef Py_UNICODE_WIDE
7170 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007171 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007172 }
7173#endif
7174 if (c == 0)
7175 return 0;
7176 /* level 1*/
7177 i = map->level1[l1];
7178 if (i == 0xFF) {
7179 return -1;
7180 }
7181 /* level 2*/
7182 i = map->level23[16*i+l2];
7183 if (i == 0xFF) {
7184 return -1;
7185 }
7186 /* level 3 */
7187 i = map->level23[16*map->count2 + 128*i + l3];
7188 if (i == 0) {
7189 return -1;
7190 }
7191 return i;
7192}
7193
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007194/* Lookup the character ch in the mapping. If the character
7195 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007196 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007197static PyObject *
7198charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007199{
Christian Heimes217cfd12007-12-02 14:31:20 +00007200 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007201 PyObject *x;
7202
7203 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007204 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007205 x = PyObject_GetItem(mapping, w);
7206 Py_DECREF(w);
7207 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007208 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7209 /* No mapping found means: mapping is undefined. */
7210 PyErr_Clear();
7211 x = Py_None;
7212 Py_INCREF(x);
7213 return x;
7214 } else
7215 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007216 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007217 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007218 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007219 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007220 long value = PyLong_AS_LONG(x);
7221 if (value < 0 || value > 255) {
7222 PyErr_SetString(PyExc_TypeError,
7223 "character mapping must be in range(256)");
7224 Py_DECREF(x);
7225 return NULL;
7226 }
7227 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007228 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007229 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007230 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007231 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007232 /* wrong return value */
7233 PyErr_Format(PyExc_TypeError,
7234 "character mapping must return integer, bytes or None, not %.400s",
7235 x->ob_type->tp_name);
7236 Py_DECREF(x);
7237 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007238 }
7239}
7240
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007241static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007242charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007243{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007244 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7245 /* exponentially overallocate to minimize reallocations */
7246 if (requiredsize < 2*outsize)
7247 requiredsize = 2*outsize;
7248 if (_PyBytes_Resize(outobj, requiredsize))
7249 return -1;
7250 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007251}
7252
Benjamin Peterson14339b62009-01-31 16:36:08 +00007253typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007255} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007256/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007257 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007258 space is available. Return a new reference to the object that
7259 was put in the output buffer, or Py_None, if the mapping was undefined
7260 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007261 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007262static charmapencode_result
7263charmapencode_output(Py_UNICODE c, PyObject *mapping,
7264 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007265{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007266 PyObject *rep;
7267 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007268 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007269
Christian Heimes90aa7642007-12-19 02:45:37 +00007270 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007271 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007272 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007273 if (res == -1)
7274 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007275 if (outsize<requiredsize)
7276 if (charmapencode_resize(outobj, outpos, requiredsize))
7277 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007278 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007279 outstart[(*outpos)++] = (char)res;
7280 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007281 }
7282
7283 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007284 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007285 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007286 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007287 Py_DECREF(rep);
7288 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007289 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007290 if (PyLong_Check(rep)) {
7291 Py_ssize_t requiredsize = *outpos+1;
7292 if (outsize<requiredsize)
7293 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7294 Py_DECREF(rep);
7295 return enc_EXCEPTION;
7296 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007297 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007298 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007299 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007300 else {
7301 const char *repchars = PyBytes_AS_STRING(rep);
7302 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7303 Py_ssize_t requiredsize = *outpos+repsize;
7304 if (outsize<requiredsize)
7305 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7306 Py_DECREF(rep);
7307 return enc_EXCEPTION;
7308 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007309 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007310 memcpy(outstart + *outpos, repchars, repsize);
7311 *outpos += repsize;
7312 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007313 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007314 Py_DECREF(rep);
7315 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007316}
7317
7318/* handle an error in PyUnicode_EncodeCharmap
7319 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007320static int
7321charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007322 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007323 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007324 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007325 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007326{
7327 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007328 Py_ssize_t repsize;
7329 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007330 Py_UNICODE *uni2;
7331 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007332 Py_ssize_t collstartpos = *inpos;
7333 Py_ssize_t collendpos = *inpos+1;
7334 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007335 char *encoding = "charmap";
7336 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007337 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007338
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007339 /* find all unencodable characters */
7340 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007341 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007342 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007343 int res = encoding_map_lookup(p[collendpos], mapping);
7344 if (res != -1)
7345 break;
7346 ++collendpos;
7347 continue;
7348 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007349
Benjamin Peterson29060642009-01-31 22:14:21 +00007350 rep = charmapencode_lookup(p[collendpos], mapping);
7351 if (rep==NULL)
7352 return -1;
7353 else if (rep!=Py_None) {
7354 Py_DECREF(rep);
7355 break;
7356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007357 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007359 }
7360 /* cache callback name lookup
7361 * (if not done yet, i.e. it's the first error) */
7362 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 if ((errors==NULL) || (!strcmp(errors, "strict")))
7364 *known_errorHandler = 1;
7365 else if (!strcmp(errors, "replace"))
7366 *known_errorHandler = 2;
7367 else if (!strcmp(errors, "ignore"))
7368 *known_errorHandler = 3;
7369 else if (!strcmp(errors, "xmlcharrefreplace"))
7370 *known_errorHandler = 4;
7371 else
7372 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007373 }
7374 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007375 case 1: /* strict */
7376 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7377 return -1;
7378 case 2: /* replace */
7379 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007380 x = charmapencode_output('?', mapping, res, respos);
7381 if (x==enc_EXCEPTION) {
7382 return -1;
7383 }
7384 else if (x==enc_FAILED) {
7385 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7386 return -1;
7387 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007388 }
7389 /* fall through */
7390 case 3: /* ignore */
7391 *inpos = collendpos;
7392 break;
7393 case 4: /* xmlcharrefreplace */
7394 /* generate replacement (temporarily (mis)uses p) */
7395 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007396 char buffer[2+29+1+1];
7397 char *cp;
7398 sprintf(buffer, "&#%d;", (int)p[collpos]);
7399 for (cp = buffer; *cp; ++cp) {
7400 x = charmapencode_output(*cp, mapping, res, respos);
7401 if (x==enc_EXCEPTION)
7402 return -1;
7403 else if (x==enc_FAILED) {
7404 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7405 return -1;
7406 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007407 }
7408 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007409 *inpos = collendpos;
7410 break;
7411 default:
7412 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007413 encoding, reason, p, size, exceptionObject,
7414 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007415 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007416 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007417 if (PyBytes_Check(repunicode)) {
7418 /* Directly copy bytes result to output. */
7419 Py_ssize_t outsize = PyBytes_Size(*res);
7420 Py_ssize_t requiredsize;
7421 repsize = PyBytes_Size(repunicode);
7422 requiredsize = *respos + repsize;
7423 if (requiredsize > outsize)
7424 /* Make room for all additional bytes. */
7425 if (charmapencode_resize(res, respos, requiredsize)) {
7426 Py_DECREF(repunicode);
7427 return -1;
7428 }
7429 memcpy(PyBytes_AsString(*res) + *respos,
7430 PyBytes_AsString(repunicode), repsize);
7431 *respos += repsize;
7432 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007433 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007434 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007435 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007436 /* generate replacement */
7437 repsize = PyUnicode_GET_SIZE(repunicode);
7438 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007439 x = charmapencode_output(*uni2, mapping, res, respos);
7440 if (x==enc_EXCEPTION) {
7441 return -1;
7442 }
7443 else if (x==enc_FAILED) {
7444 Py_DECREF(repunicode);
7445 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7446 return -1;
7447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007448 }
7449 *inpos = newpos;
7450 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007451 }
7452 return 0;
7453}
7454
Alexander Belopolsky40018472011-02-26 01:02:56 +00007455PyObject *
7456PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7457 Py_ssize_t size,
7458 PyObject *mapping,
7459 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007460{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007461 /* output object */
7462 PyObject *res = NULL;
7463 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007464 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007465 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007466 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007467 PyObject *errorHandler = NULL;
7468 PyObject *exc = NULL;
7469 /* the following variable is used for caching string comparisons
7470 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7471 * 3=ignore, 4=xmlcharrefreplace */
7472 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007473
7474 /* Default to Latin-1 */
7475 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007476 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007477
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007478 /* allocate enough for a simple encoding without
7479 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007480 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007481 if (res == NULL)
7482 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007483 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007484 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007485
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007486 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007487 /* try to encode it */
7488 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7489 if (x==enc_EXCEPTION) /* error */
7490 goto onError;
7491 if (x==enc_FAILED) { /* unencodable character */
7492 if (charmap_encoding_error(p, size, &inpos, mapping,
7493 &exc,
7494 &known_errorHandler, &errorHandler, errors,
7495 &res, &respos)) {
7496 goto onError;
7497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007498 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 else
7500 /* done with this character => adjust input position */
7501 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007502 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007503
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007504 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007505 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007506 if (_PyBytes_Resize(&res, respos) < 0)
7507 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007508
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007509 Py_XDECREF(exc);
7510 Py_XDECREF(errorHandler);
7511 return res;
7512
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007514 Py_XDECREF(res);
7515 Py_XDECREF(exc);
7516 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007517 return NULL;
7518}
7519
Alexander Belopolsky40018472011-02-26 01:02:56 +00007520PyObject *
7521PyUnicode_AsCharmapString(PyObject *unicode,
7522 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007523{
7524 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007525 PyErr_BadArgument();
7526 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007527 }
7528 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007529 PyUnicode_GET_SIZE(unicode),
7530 mapping,
7531 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007532}
7533
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007534/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007535static void
7536make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007537 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007538 Py_ssize_t startpos, Py_ssize_t endpos,
7539 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007540{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007541 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007542 *exceptionObject = _PyUnicodeTranslateError_Create(
7543 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007544 }
7545 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007546 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7547 goto onError;
7548 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7549 goto onError;
7550 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7551 goto onError;
7552 return;
7553 onError:
7554 Py_DECREF(*exceptionObject);
7555 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007556 }
7557}
7558
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007559/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007560static void
7561raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007562 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007563 Py_ssize_t startpos, Py_ssize_t endpos,
7564 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007565{
7566 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007567 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007568 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007570}
7571
7572/* error handling callback helper:
7573 build arguments, call the callback and check the arguments,
7574 put the result into newpos and return the replacement string, which
7575 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007576static PyObject *
7577unicode_translate_call_errorhandler(const char *errors,
7578 PyObject **errorHandler,
7579 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007580 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007581 Py_ssize_t startpos, Py_ssize_t endpos,
7582 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007583{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007584 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007585
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007586 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007587 PyObject *restuple;
7588 PyObject *resunicode;
7589
7590 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007592 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007593 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007594 }
7595
7596 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007597 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007598 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007600
7601 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007602 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007603 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007604 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007606 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007607 Py_DECREF(restuple);
7608 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007609 }
7610 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007611 &resunicode, &i_newpos)) {
7612 Py_DECREF(restuple);
7613 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007614 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007615 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007616 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007617 else
7618 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007619 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7621 Py_DECREF(restuple);
7622 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007623 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007624 Py_INCREF(resunicode);
7625 Py_DECREF(restuple);
7626 return resunicode;
7627}
7628
7629/* Lookup the character ch in the mapping and put the result in result,
7630 which must be decrefed by the caller.
7631 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007632static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007633charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007634{
Christian Heimes217cfd12007-12-02 14:31:20 +00007635 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007636 PyObject *x;
7637
7638 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007640 x = PyObject_GetItem(mapping, w);
7641 Py_DECREF(w);
7642 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007643 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7644 /* No mapping found means: use 1:1 mapping. */
7645 PyErr_Clear();
7646 *result = NULL;
7647 return 0;
7648 } else
7649 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007650 }
7651 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007652 *result = x;
7653 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007654 }
Christian Heimes217cfd12007-12-02 14:31:20 +00007655 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007656 long value = PyLong_AS_LONG(x);
7657 long max = PyUnicode_GetMax();
7658 if (value < 0 || value > max) {
7659 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00007660 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00007661 Py_DECREF(x);
7662 return -1;
7663 }
7664 *result = x;
7665 return 0;
7666 }
7667 else if (PyUnicode_Check(x)) {
7668 *result = x;
7669 return 0;
7670 }
7671 else {
7672 /* wrong return value */
7673 PyErr_SetString(PyExc_TypeError,
7674 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007675 Py_DECREF(x);
7676 return -1;
7677 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007678}
7679/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00007680 if not reallocate and adjust various state variables.
7681 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007682static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007683charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00007684 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007686 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00007687 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007688 /* exponentially overallocate to minimize reallocations */
7689 if (requiredsize < 2 * oldsize)
7690 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007691 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
7692 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007693 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007694 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007695 }
7696 return 0;
7697}
7698/* lookup the character, put the result in the output string and adjust
7699 various state variables. Return a new reference to the object that
7700 was put in the output buffer in *result, or Py_None, if the mapping was
7701 undefined (in which case no character was written).
7702 The called must decref result.
7703 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007704static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007705charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
7706 PyObject *mapping, Py_UCS4 **output,
7707 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007708 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007710 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
7711 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00007712 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007713 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007715 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007716 }
7717 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007718 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00007719 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007721 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007722 }
7723 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007724 Py_ssize_t repsize;
7725 if (PyUnicode_READY(*res) == -1)
7726 return -1;
7727 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00007728 if (repsize==1) {
7729 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007730 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00007731 }
7732 else if (repsize!=0) {
7733 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007734 Py_ssize_t requiredsize = *opos +
7735 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007737 Py_ssize_t i;
7738 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00007739 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007740 for(i = 0; i < repsize; i++)
7741 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007743 }
7744 else
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007746 return 0;
7747}
7748
Alexander Belopolsky40018472011-02-26 01:02:56 +00007749PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007750_PyUnicode_TranslateCharmap(PyObject *input,
7751 PyObject *mapping,
7752 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007754 /* input object */
7755 char *idata;
7756 Py_ssize_t size, i;
7757 int kind;
7758 /* output buffer */
7759 Py_UCS4 *output = NULL;
7760 Py_ssize_t osize;
7761 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007762 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007763 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007764 char *reason = "character maps to <undefined>";
7765 PyObject *errorHandler = NULL;
7766 PyObject *exc = NULL;
7767 /* the following variable is used for caching string comparisons
7768 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7769 * 3=ignore, 4=xmlcharrefreplace */
7770 int known_errorHandler = -1;
7771
Guido van Rossumd57fd912000-03-10 22:53:23 +00007772 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 PyErr_BadArgument();
7774 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007777 if (PyUnicode_READY(input) == -1)
7778 return NULL;
7779 idata = (char*)PyUnicode_DATA(input);
7780 kind = PyUnicode_KIND(input);
7781 size = PyUnicode_GET_LENGTH(input);
7782 i = 0;
7783
7784 if (size == 0) {
7785 Py_INCREF(input);
7786 return input;
7787 }
7788
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007789 /* allocate enough for a simple 1:1 translation without
7790 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007791 osize = size;
7792 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
7793 opos = 0;
7794 if (output == NULL) {
7795 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007796 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007797 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007799 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 /* try to encode it */
7801 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007802 if (charmaptranslate_output(input, i, mapping,
7803 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 Py_XDECREF(x);
7805 goto onError;
7806 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007807 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00007808 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007809 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00007810 else { /* untranslatable character */
7811 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
7812 Py_ssize_t repsize;
7813 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007814 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00007815 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007816 Py_ssize_t collstart = i;
7817 Py_ssize_t collend = i+1;
7818 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007821 while (collend < size) {
7822 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007823 goto onError;
7824 Py_XDECREF(x);
7825 if (x!=Py_None)
7826 break;
7827 ++collend;
7828 }
7829 /* cache callback name lookup
7830 * (if not done yet, i.e. it's the first error) */
7831 if (known_errorHandler==-1) {
7832 if ((errors==NULL) || (!strcmp(errors, "strict")))
7833 known_errorHandler = 1;
7834 else if (!strcmp(errors, "replace"))
7835 known_errorHandler = 2;
7836 else if (!strcmp(errors, "ignore"))
7837 known_errorHandler = 3;
7838 else if (!strcmp(errors, "xmlcharrefreplace"))
7839 known_errorHandler = 4;
7840 else
7841 known_errorHandler = 0;
7842 }
7843 switch (known_errorHandler) {
7844 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007845 raise_translate_exception(&exc, input, collstart,
7846 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007847 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 case 2: /* replace */
7849 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007850 for (coll = collstart; coll<collend; coll++)
7851 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00007852 /* fall through */
7853 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007854 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007855 break;
7856 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007857 /* generate replacement (temporarily (mis)uses i) */
7858 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 char buffer[2+29+1+1];
7860 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007861 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
7862 if (charmaptranslate_makespace(&output, &osize,
7863 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00007864 goto onError;
7865 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007866 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007868 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 break;
7870 default:
7871 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007872 reason, input, &exc,
7873 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007874 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00007875 goto onError;
7876 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007877 repsize = PyUnicode_GET_LENGTH(repunicode);
7878 if (charmaptranslate_makespace(&output, &osize,
7879 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 Py_DECREF(repunicode);
7881 goto onError;
7882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007883 for (uni2 = 0; repsize-->0; ++uni2)
7884 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
7885 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00007886 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007887 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007888 }
7889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007890 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
7891 if (!res)
7892 goto onError;
7893 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007894 Py_XDECREF(exc);
7895 Py_XDECREF(errorHandler);
7896 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007897
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007899 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007900 Py_XDECREF(exc);
7901 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007902 return NULL;
7903}
7904
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007905/* Deprecated. Use PyUnicode_Translate instead. */
7906PyObject *
7907PyUnicode_TranslateCharmap(const Py_UNICODE *p,
7908 Py_ssize_t size,
7909 PyObject *mapping,
7910 const char *errors)
7911{
7912 PyObject *unicode = PyUnicode_FromUnicode(p, size);
7913 if (!unicode)
7914 return NULL;
7915 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
7916}
7917
Alexander Belopolsky40018472011-02-26 01:02:56 +00007918PyObject *
7919PyUnicode_Translate(PyObject *str,
7920 PyObject *mapping,
7921 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007922{
7923 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00007924
Guido van Rossumd57fd912000-03-10 22:53:23 +00007925 str = PyUnicode_FromObject(str);
7926 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007927 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007928 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007929 Py_DECREF(str);
7930 return result;
Tim Petersced69f82003-09-16 20:30:58 +00007931
Benjamin Peterson29060642009-01-31 22:14:21 +00007932 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933 Py_XDECREF(str);
7934 return NULL;
7935}
Tim Petersced69f82003-09-16 20:30:58 +00007936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007937static Py_UCS4
7938fix_decimal_and_space_to_ascii(PyUnicodeObject *self)
7939{
7940 /* No need to call PyUnicode_READY(self) because this function is only
7941 called as a callback from fixup() which does it already. */
7942 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
7943 const int kind = PyUnicode_KIND(self);
7944 void *data = PyUnicode_DATA(self);
7945 Py_UCS4 maxchar = 0, ch, fixed;
7946 Py_ssize_t i;
7947
7948 for (i = 0; i < len; ++i) {
7949 ch = PyUnicode_READ(kind, data, i);
7950 fixed = 0;
7951 if (ch > 127) {
7952 if (Py_UNICODE_ISSPACE(ch))
7953 fixed = ' ';
7954 else {
7955 const int decimal = Py_UNICODE_TODECIMAL(ch);
7956 if (decimal >= 0)
7957 fixed = '0' + decimal;
7958 }
7959 if (fixed != 0) {
7960 if (fixed > maxchar)
7961 maxchar = fixed;
7962 PyUnicode_WRITE(kind, data, i, fixed);
7963 }
7964 else if (ch > maxchar)
7965 maxchar = ch;
7966 }
7967 else if (ch > maxchar)
7968 maxchar = ch;
7969 }
7970
7971 return maxchar;
7972}
7973
7974PyObject *
7975_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
7976{
7977 if (!PyUnicode_Check(unicode)) {
7978 PyErr_BadInternalCall();
7979 return NULL;
7980 }
7981 if (PyUnicode_READY(unicode) == -1)
7982 return NULL;
7983 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
7984 /* If the string is already ASCII, just return the same string */
7985 Py_INCREF(unicode);
7986 return unicode;
7987 }
7988 return fixup((PyUnicodeObject *)unicode, fix_decimal_and_space_to_ascii);
7989}
7990
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00007991PyObject *
7992PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
7993 Py_ssize_t length)
7994{
7995 PyObject *result;
7996 Py_UNICODE *p; /* write pointer into result */
7997 Py_ssize_t i;
7998 /* Copy to a new string */
7999 result = (PyObject *)_PyUnicode_New(length);
8000 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8001 if (result == NULL)
8002 return result;
8003 p = PyUnicode_AS_UNICODE(result);
8004 /* Iterate over code points */
8005 for (i = 0; i < length; i++) {
8006 Py_UNICODE ch =s[i];
8007 if (ch > 127) {
8008 int decimal = Py_UNICODE_TODECIMAL(ch);
8009 if (decimal >= 0)
8010 p[i] = '0' + decimal;
8011 }
8012 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008013 if (PyUnicode_READY((PyUnicodeObject*)result) == -1) {
8014 Py_DECREF(result);
8015 return NULL;
8016 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008017 return result;
8018}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008019/* --- Decimal Encoder ---------------------------------------------------- */
8020
Alexander Belopolsky40018472011-02-26 01:02:56 +00008021int
8022PyUnicode_EncodeDecimal(Py_UNICODE *s,
8023 Py_ssize_t length,
8024 char *output,
8025 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008026{
8027 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008028 PyObject *errorHandler = NULL;
8029 PyObject *exc = NULL;
8030 const char *encoding = "decimal";
8031 const char *reason = "invalid decimal Unicode string";
8032 /* the following variable is used for caching string comparisons
8033 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8034 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008035
8036 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 PyErr_BadArgument();
8038 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008039 }
8040
8041 p = s;
8042 end = s + length;
8043 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 register Py_UNICODE ch = *p;
8045 int decimal;
8046 PyObject *repunicode;
8047 Py_ssize_t repsize;
8048 Py_ssize_t newpos;
8049 Py_UNICODE *uni2;
8050 Py_UNICODE *collstart;
8051 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008052
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008054 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008055 ++p;
8056 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008057 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 decimal = Py_UNICODE_TODECIMAL(ch);
8059 if (decimal >= 0) {
8060 *output++ = '0' + decimal;
8061 ++p;
8062 continue;
8063 }
8064 if (0 < ch && ch < 256) {
8065 *output++ = (char)ch;
8066 ++p;
8067 continue;
8068 }
8069 /* All other characters are considered unencodable */
8070 collstart = p;
8071 collend = p+1;
8072 while (collend < end) {
8073 if ((0 < *collend && *collend < 256) ||
8074 !Py_UNICODE_ISSPACE(*collend) ||
8075 Py_UNICODE_TODECIMAL(*collend))
8076 break;
8077 }
8078 /* cache callback name lookup
8079 * (if not done yet, i.e. it's the first error) */
8080 if (known_errorHandler==-1) {
8081 if ((errors==NULL) || (!strcmp(errors, "strict")))
8082 known_errorHandler = 1;
8083 else if (!strcmp(errors, "replace"))
8084 known_errorHandler = 2;
8085 else if (!strcmp(errors, "ignore"))
8086 known_errorHandler = 3;
8087 else if (!strcmp(errors, "xmlcharrefreplace"))
8088 known_errorHandler = 4;
8089 else
8090 known_errorHandler = 0;
8091 }
8092 switch (known_errorHandler) {
8093 case 1: /* strict */
8094 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8095 goto onError;
8096 case 2: /* replace */
8097 for (p = collstart; p < collend; ++p)
8098 *output++ = '?';
8099 /* fall through */
8100 case 3: /* ignore */
8101 p = collend;
8102 break;
8103 case 4: /* xmlcharrefreplace */
8104 /* generate replacement (temporarily (mis)uses p) */
8105 for (p = collstart; p < collend; ++p)
8106 output += sprintf(output, "&#%d;", (int)*p);
8107 p = collend;
8108 break;
8109 default:
8110 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8111 encoding, reason, s, length, &exc,
8112 collstart-s, collend-s, &newpos);
8113 if (repunicode == NULL)
8114 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008115 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008116 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008117 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8118 Py_DECREF(repunicode);
8119 goto onError;
8120 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 /* generate replacement */
8122 repsize = PyUnicode_GET_SIZE(repunicode);
8123 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8124 Py_UNICODE ch = *uni2;
8125 if (Py_UNICODE_ISSPACE(ch))
8126 *output++ = ' ';
8127 else {
8128 decimal = Py_UNICODE_TODECIMAL(ch);
8129 if (decimal >= 0)
8130 *output++ = '0' + decimal;
8131 else if (0 < ch && ch < 256)
8132 *output++ = (char)ch;
8133 else {
8134 Py_DECREF(repunicode);
8135 raise_encode_exception(&exc, encoding,
8136 s, length, collstart-s, collend-s, reason);
8137 goto onError;
8138 }
8139 }
8140 }
8141 p = s + newpos;
8142 Py_DECREF(repunicode);
8143 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008144 }
8145 /* 0-terminate the output string */
8146 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 Py_XDECREF(exc);
8148 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008149 return 0;
8150
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 Py_XDECREF(exc);
8153 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008154 return -1;
8155}
8156
Guido van Rossumd57fd912000-03-10 22:53:23 +00008157/* --- Helpers ------------------------------------------------------------ */
8158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008159#include "stringlib/ucs1lib.h"
8160#include "stringlib/fastsearch.h"
8161#include "stringlib/partition.h"
8162#include "stringlib/split.h"
8163#include "stringlib/count.h"
8164#include "stringlib/find.h"
8165#include "stringlib/localeutil.h"
8166#include "stringlib/undef.h"
8167
8168#include "stringlib/ucs2lib.h"
8169#include "stringlib/fastsearch.h"
8170#include "stringlib/partition.h"
8171#include "stringlib/split.h"
8172#include "stringlib/count.h"
8173#include "stringlib/find.h"
8174#include "stringlib/localeutil.h"
8175#include "stringlib/undef.h"
8176
8177#include "stringlib/ucs4lib.h"
8178#include "stringlib/fastsearch.h"
8179#include "stringlib/partition.h"
8180#include "stringlib/split.h"
8181#include "stringlib/count.h"
8182#include "stringlib/find.h"
8183#include "stringlib/localeutil.h"
8184#include "stringlib/undef.h"
8185
8186static Py_ssize_t
8187any_find_slice(Py_ssize_t Py_LOCAL_CALLBACK(ucs1)(const Py_UCS1*, Py_ssize_t,
8188 const Py_UCS1*, Py_ssize_t,
8189 Py_ssize_t, Py_ssize_t),
8190 Py_ssize_t Py_LOCAL_CALLBACK(ucs2)(const Py_UCS2*, Py_ssize_t,
8191 const Py_UCS2*, Py_ssize_t,
8192 Py_ssize_t, Py_ssize_t),
8193 Py_ssize_t Py_LOCAL_CALLBACK(ucs4)(const Py_UCS4*, Py_ssize_t,
8194 const Py_UCS4*, Py_ssize_t,
8195 Py_ssize_t, Py_ssize_t),
8196 PyObject* s1, PyObject* s2,
8197 Py_ssize_t start,
8198 Py_ssize_t end)
8199{
8200 int kind1, kind2, kind;
8201 void *buf1, *buf2;
8202 Py_ssize_t len1, len2, result;
8203
8204 kind1 = PyUnicode_KIND(s1);
8205 kind2 = PyUnicode_KIND(s2);
8206 kind = kind1 > kind2 ? kind1 : kind2;
8207 buf1 = PyUnicode_DATA(s1);
8208 buf2 = PyUnicode_DATA(s2);
8209 if (kind1 != kind)
8210 buf1 = _PyUnicode_AsKind(s1, kind);
8211 if (!buf1)
8212 return -2;
8213 if (kind2 != kind)
8214 buf2 = _PyUnicode_AsKind(s2, kind);
8215 if (!buf2) {
8216 if (kind1 != kind) PyMem_Free(buf1);
8217 return -2;
8218 }
8219 len1 = PyUnicode_GET_LENGTH(s1);
8220 len2 = PyUnicode_GET_LENGTH(s2);
8221
8222 switch(kind) {
8223 case PyUnicode_1BYTE_KIND:
8224 result = ucs1(buf1, len1, buf2, len2, start, end);
8225 break;
8226 case PyUnicode_2BYTE_KIND:
8227 result = ucs2(buf1, len1, buf2, len2, start, end);
8228 break;
8229 case PyUnicode_4BYTE_KIND:
8230 result = ucs4(buf1, len1, buf2, len2, start, end);
8231 break;
8232 default:
8233 assert(0); result = -2;
8234 }
8235
8236 if (kind1 != kind)
8237 PyMem_Free(buf1);
8238 if (kind2 != kind)
8239 PyMem_Free(buf2);
8240
8241 return result;
8242}
8243
8244Py_ssize_t
8245_PyUnicode_InsertThousandsGrouping(int kind, void *data,
8246 Py_ssize_t n_buffer,
8247 void *digits, Py_ssize_t n_digits,
8248 Py_ssize_t min_width,
8249 const char *grouping,
8250 const char *thousands_sep)
8251{
8252 switch(kind) {
8253 case PyUnicode_1BYTE_KIND:
8254 return _PyUnicode_ucs1_InsertThousandsGrouping(
8255 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8256 min_width, grouping, thousands_sep);
8257 case PyUnicode_2BYTE_KIND:
8258 return _PyUnicode_ucs2_InsertThousandsGrouping(
8259 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8260 min_width, grouping, thousands_sep);
8261 case PyUnicode_4BYTE_KIND:
8262 return _PyUnicode_ucs4_InsertThousandsGrouping(
8263 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8264 min_width, grouping, thousands_sep);
8265 }
8266 assert(0);
8267 return -1;
8268}
8269
8270
Eric Smith8c663262007-08-25 02:26:07 +00008271#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008272#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008273
Thomas Wouters477c8d52006-05-27 19:21:47 +00008274#include "stringlib/count.h"
8275#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008276
Thomas Wouters477c8d52006-05-27 19:21:47 +00008277/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008278#define ADJUST_INDICES(start, end, len) \
8279 if (end > len) \
8280 end = len; \
8281 else if (end < 0) { \
8282 end += len; \
8283 if (end < 0) \
8284 end = 0; \
8285 } \
8286 if (start < 0) { \
8287 start += len; \
8288 if (start < 0) \
8289 start = 0; \
8290 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008291
Alexander Belopolsky40018472011-02-26 01:02:56 +00008292Py_ssize_t
8293PyUnicode_Count(PyObject *str,
8294 PyObject *substr,
8295 Py_ssize_t start,
8296 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008297{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008298 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008299 PyUnicodeObject* str_obj;
8300 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008301 int kind1, kind2, kind;
8302 void *buf1 = NULL, *buf2 = NULL;
8303 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008304
Thomas Wouters477c8d52006-05-27 19:21:47 +00008305 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008306 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008308 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008309 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 Py_DECREF(str_obj);
8311 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312 }
Tim Petersced69f82003-09-16 20:30:58 +00008313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008314 kind1 = PyUnicode_KIND(str_obj);
8315 kind2 = PyUnicode_KIND(sub_obj);
8316 kind = kind1 > kind2 ? kind1 : kind2;
8317 buf1 = PyUnicode_DATA(str_obj);
8318 if (kind1 != kind)
8319 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8320 if (!buf1)
8321 goto onError;
8322 buf2 = PyUnicode_DATA(sub_obj);
8323 if (kind2 != kind)
8324 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8325 if (!buf2)
8326 goto onError;
8327 len1 = PyUnicode_GET_LENGTH(str_obj);
8328 len2 = PyUnicode_GET_LENGTH(sub_obj);
8329
8330 ADJUST_INDICES(start, end, len1);
8331 switch(kind) {
8332 case PyUnicode_1BYTE_KIND:
8333 result = ucs1lib_count(
8334 ((Py_UCS1*)buf1) + start, end - start,
8335 buf2, len2, PY_SSIZE_T_MAX
8336 );
8337 break;
8338 case PyUnicode_2BYTE_KIND:
8339 result = ucs2lib_count(
8340 ((Py_UCS2*)buf1) + start, end - start,
8341 buf2, len2, PY_SSIZE_T_MAX
8342 );
8343 break;
8344 case PyUnicode_4BYTE_KIND:
8345 result = ucs4lib_count(
8346 ((Py_UCS4*)buf1) + start, end - start,
8347 buf2, len2, PY_SSIZE_T_MAX
8348 );
8349 break;
8350 default:
8351 assert(0); result = 0;
8352 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008353
8354 Py_DECREF(sub_obj);
8355 Py_DECREF(str_obj);
8356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008357 if (kind1 != kind)
8358 PyMem_Free(buf1);
8359 if (kind2 != kind)
8360 PyMem_Free(buf2);
8361
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008363 onError:
8364 Py_DECREF(sub_obj);
8365 Py_DECREF(str_obj);
8366 if (kind1 != kind && buf1)
8367 PyMem_Free(buf1);
8368 if (kind2 != kind && buf2)
8369 PyMem_Free(buf2);
8370 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008371}
8372
Alexander Belopolsky40018472011-02-26 01:02:56 +00008373Py_ssize_t
8374PyUnicode_Find(PyObject *str,
8375 PyObject *sub,
8376 Py_ssize_t start,
8377 Py_ssize_t end,
8378 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008379{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008380 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008381
Guido van Rossumd57fd912000-03-10 22:53:23 +00008382 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008385 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008386 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 Py_DECREF(str);
8388 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008389 }
Tim Petersced69f82003-09-16 20:30:58 +00008390
Thomas Wouters477c8d52006-05-27 19:21:47 +00008391 if (direction > 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008392 result = any_find_slice(
8393 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
8394 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008395 );
8396 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397 result = any_find_slice(
8398 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
8399 str, sub, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +00008400 );
8401
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008403 Py_DECREF(sub);
8404
Guido van Rossumd57fd912000-03-10 22:53:23 +00008405 return result;
8406}
8407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408Py_ssize_t
8409PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8410 Py_ssize_t start, Py_ssize_t end,
8411 int direction)
8412{
8413 char *result;
8414 int kind;
8415 if (PyUnicode_READY(str) == -1)
8416 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008417 if (start < 0 || end < 0) {
8418 PyErr_SetString(PyExc_IndexError, "string index out of range");
8419 return -2;
8420 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008421 if (end > PyUnicode_GET_LENGTH(str))
8422 end = PyUnicode_GET_LENGTH(str);
8423 kind = PyUnicode_KIND(str);
8424 result = findchar(PyUnicode_1BYTE_DATA(str)
8425 + PyUnicode_KIND_SIZE(kind, start),
8426 kind,
8427 end-start, ch, direction);
8428 if (!result)
8429 return -1;
8430 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8431}
8432
Alexander Belopolsky40018472011-02-26 01:02:56 +00008433static int
8434tailmatch(PyUnicodeObject *self,
8435 PyUnicodeObject *substring,
8436 Py_ssize_t start,
8437 Py_ssize_t end,
8438 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008439{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008440 int kind_self;
8441 int kind_sub;
8442 void *data_self;
8443 void *data_sub;
8444 Py_ssize_t offset;
8445 Py_ssize_t i;
8446 Py_ssize_t end_sub;
8447
8448 if (PyUnicode_READY(self) == -1 ||
8449 PyUnicode_READY(substring) == -1)
8450 return 0;
8451
8452 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008453 return 1;
8454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8456 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008457 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 kind_self = PyUnicode_KIND(self);
8461 data_self = PyUnicode_DATA(self);
8462 kind_sub = PyUnicode_KIND(substring);
8463 data_sub = PyUnicode_DATA(substring);
8464 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8465
8466 if (direction > 0)
8467 offset = end;
8468 else
8469 offset = start;
8470
8471 if (PyUnicode_READ(kind_self, data_self, offset) ==
8472 PyUnicode_READ(kind_sub, data_sub, 0) &&
8473 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8474 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8475 /* If both are of the same kind, memcmp is sufficient */
8476 if (kind_self == kind_sub) {
8477 return ! memcmp((char *)data_self +
8478 (offset * PyUnicode_CHARACTER_SIZE(substring)),
8479 data_sub,
8480 PyUnicode_GET_LENGTH(substring) *
8481 PyUnicode_CHARACTER_SIZE(substring));
8482 }
8483 /* otherwise we have to compare each character by first accesing it */
8484 else {
8485 /* We do not need to compare 0 and len(substring)-1 because
8486 the if statement above ensured already that they are equal
8487 when we end up here. */
8488 // TODO: honor direction and do a forward or backwards search
8489 for (i = 1; i < end_sub; ++i) {
8490 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8491 PyUnicode_READ(kind_sub, data_sub, i))
8492 return 0;
8493 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496 }
8497
8498 return 0;
8499}
8500
Alexander Belopolsky40018472011-02-26 01:02:56 +00008501Py_ssize_t
8502PyUnicode_Tailmatch(PyObject *str,
8503 PyObject *substr,
8504 Py_ssize_t start,
8505 Py_ssize_t end,
8506 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008507{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008508 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008509
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510 str = PyUnicode_FromObject(str);
8511 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513 substr = PyUnicode_FromObject(substr);
8514 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 Py_DECREF(str);
8516 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008517 }
Tim Petersced69f82003-09-16 20:30:58 +00008518
Guido van Rossumd57fd912000-03-10 22:53:23 +00008519 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 (PyUnicodeObject *)substr,
8521 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522 Py_DECREF(str);
8523 Py_DECREF(substr);
8524 return result;
8525}
8526
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527/* Apply fixfct filter to the Unicode object self and return a
8528 reference to the modified object */
8529
Alexander Belopolsky40018472011-02-26 01:02:56 +00008530static PyObject *
8531fixup(PyUnicodeObject *self,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 Py_UCS4 (*fixfct)(PyUnicodeObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 PyObject *u;
8535 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 if (PyUnicode_READY(self) == -1)
8538 return NULL;
8539 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8540 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8541 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008545 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
8546 PyUnicode_GET_LENGTH(u) * PyUnicode_CHARACTER_SIZE(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008548 /* fix functions return the new maximum character in a string,
8549 if the kind of the resulting unicode object does not change,
8550 everything is fine. Otherwise we need to change the string kind
8551 and re-run the fix function. */
8552 maxchar_new = fixfct((PyUnicodeObject*)u);
8553 if (maxchar_new == 0)
8554 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8555 else if (maxchar_new <= 127)
8556 maxchar_new = 127;
8557 else if (maxchar_new <= 255)
8558 maxchar_new = 255;
8559 else if (maxchar_new <= 65535)
8560 maxchar_new = 65535;
8561 else
8562 maxchar_new = 1114111; /* 0x10ffff */
8563
8564 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 /* fixfct should return TRUE if it modified the buffer. If
8566 FALSE, return a reference to the original buffer instead
8567 (to save space, not time) */
8568 Py_INCREF(self);
8569 Py_DECREF(u);
8570 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 else if (maxchar_new == maxchar_old) {
8573 return u;
8574 }
8575 else {
8576 /* In case the maximum character changed, we need to
8577 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008578 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 if (v == NULL) {
8580 Py_DECREF(u);
8581 return NULL;
8582 }
8583 if (maxchar_new > maxchar_old) {
8584 /* If the maxchar increased so that the kind changed, not all
8585 characters are representable anymore and we need to fix the
8586 string again. This only happens in very few cases. */
Victor Stinner157f83f2011-09-28 21:41:31 +02008587 if (PyUnicode_CopyCharacters(v, 0,
8588 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008589 PyUnicode_GET_LENGTH(self)) < 0)
8590 {
8591 Py_DECREF(u);
8592 return NULL;
8593 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008594 maxchar_old = fixfct((PyUnicodeObject*)v);
8595 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8596 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008597 else {
Victor Stinner157f83f2011-09-28 21:41:31 +02008598 if (PyUnicode_CopyCharacters(v, 0,
8599 u, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008600 PyUnicode_GET_LENGTH(self)) < 0)
8601 {
8602 Py_DECREF(u);
8603 return NULL;
8604 }
8605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606
8607 Py_DECREF(u);
8608 return v;
8609 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008610}
8611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008613fixupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 /* No need to call PyUnicode_READY(self) because this function is only
8616 called as a callback from fixup() which does it already. */
8617 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8618 const int kind = PyUnicode_KIND(self);
8619 void *data = PyUnicode_DATA(self);
8620 int touched = 0;
8621 Py_UCS4 maxchar = 0;
8622 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008624 for (i = 0; i < len; ++i) {
8625 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8626 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8627 if (up != ch) {
8628 if (up > maxchar)
8629 maxchar = up;
8630 PyUnicode_WRITE(kind, data, i, up);
8631 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 else if (ch > maxchar)
8634 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008635 }
8636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 if (touched)
8638 return maxchar;
8639 else
8640 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641}
8642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008644fixlower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008645{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8647 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8648 const int kind = PyUnicode_KIND(self);
8649 void *data = PyUnicode_DATA(self);
8650 int touched = 0;
8651 Py_UCS4 maxchar = 0;
8652 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008654 for(i = 0; i < len; ++i) {
8655 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8656 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8657 if (lo != ch) {
8658 if (lo > maxchar)
8659 maxchar = lo;
8660 PyUnicode_WRITE(kind, data, i, lo);
8661 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663 else if (ch > maxchar)
8664 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008665 }
8666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 if (touched)
8668 return maxchar;
8669 else
8670 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008671}
8672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008674fixswapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008676 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8677 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8678 const int kind = PyUnicode_KIND(self);
8679 void *data = PyUnicode_DATA(self);
8680 int touched = 0;
8681 Py_UCS4 maxchar = 0;
8682 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 for(i = 0; i < len; ++i) {
8685 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8686 Py_UCS4 nu = 0;
8687
8688 if (Py_UNICODE_ISUPPER(ch))
8689 nu = Py_UNICODE_TOLOWER(ch);
8690 else if (Py_UNICODE_ISLOWER(ch))
8691 nu = Py_UNICODE_TOUPPER(ch);
8692
8693 if (nu != 0) {
8694 if (nu > maxchar)
8695 maxchar = nu;
8696 PyUnicode_WRITE(kind, data, i, nu);
8697 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 else if (ch > maxchar)
8700 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008701 }
8702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 if (touched)
8704 return maxchar;
8705 else
8706 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008707}
8708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008710fixcapitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008711{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8713 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8714 const int kind = PyUnicode_KIND(self);
8715 void *data = PyUnicode_DATA(self);
8716 int touched = 0;
8717 Py_UCS4 maxchar = 0;
8718 Py_ssize_t i = 0;
8719 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00008720
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008721 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723
8724 ch = PyUnicode_READ(kind, data, i);
8725 if (!Py_UNICODE_ISUPPER(ch)) {
8726 maxchar = Py_UNICODE_TOUPPER(ch);
8727 PyUnicode_WRITE(kind, data, i, maxchar);
8728 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008730 ++i;
8731 for(; i < len; ++i) {
8732 ch = PyUnicode_READ(kind, data, i);
8733 if (!Py_UNICODE_ISLOWER(ch)) {
8734 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
8735 if (lo > maxchar)
8736 maxchar = lo;
8737 PyUnicode_WRITE(kind, data, i, lo);
8738 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008740 else if (ch > maxchar)
8741 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00008742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743
8744 if (touched)
8745 return maxchar;
8746 else
8747 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008748}
8749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750static Py_UCS4
Alexander Belopolsky40018472011-02-26 01:02:56 +00008751fixtitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008752{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
8754 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8755 const int kind = PyUnicode_KIND(self);
8756 void *data = PyUnicode_DATA(self);
8757 Py_UCS4 maxchar = 0;
8758 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008759 int previous_is_cased;
8760
8761 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008762 if (len == 1) {
8763 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8764 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
8765 if (ti != ch) {
8766 PyUnicode_WRITE(kind, data, i, ti);
8767 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 }
8769 else
8770 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 for(; i < len; ++i) {
8774 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8775 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00008776
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00008779 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 nu = Py_UNICODE_TOTITLE(ch);
8781
8782 if (nu > maxchar)
8783 maxchar = nu;
8784 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00008785
Benjamin Peterson29060642009-01-31 22:14:21 +00008786 if (Py_UNICODE_ISLOWER(ch) ||
8787 Py_UNICODE_ISUPPER(ch) ||
8788 Py_UNICODE_ISTITLE(ch))
8789 previous_is_cased = 1;
8790 else
8791 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008792 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008793 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008794}
8795
Tim Peters8ce9f162004-08-27 01:49:32 +00008796PyObject *
8797PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 PyObject *sep = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008800 Py_ssize_t seplen = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00008802 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008803 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
8804 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00008805 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806 Py_ssize_t sz, i, res_offset;
8807 Py_UCS4 maxchar = 0;
8808 Py_UCS4 item_maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008809
Tim Peters05eba1f2004-08-27 21:32:02 +00008810 fseq = PySequence_Fast(seq, "");
8811 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008812 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00008813 }
8814
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008815 /* NOTE: the following code can't call back into Python code,
8816 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00008817 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008818
Tim Peters05eba1f2004-08-27 21:32:02 +00008819 seqlen = PySequence_Fast_GET_SIZE(fseq);
8820 /* If empty sequence, return u"". */
8821 if (seqlen == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822 res = PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008823 goto Done;
Tim Peters05eba1f2004-08-27 21:32:02 +00008824 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008825 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00008826 /* If singleton sequence with an exact Unicode, return that. */
8827 if (seqlen == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008828 item = items[0];
8829 if (PyUnicode_CheckExact(item)) {
8830 Py_INCREF(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 res = item;
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 goto Done;
8833 }
Tim Peters8ce9f162004-08-27 01:49:32 +00008834 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008835 else {
8836 /* Set up sep and seplen */
8837 if (separator == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838 /* fall back to a blank space separator */
8839 sep = PyUnicode_FromOrdinal(' ');
Victor Stinnere9a29352011-10-01 02:14:59 +02008840 if (!sep)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841 goto onError;
Tim Peters05eba1f2004-08-27 21:32:02 +00008842 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008843 else {
8844 if (!PyUnicode_Check(separator)) {
8845 PyErr_Format(PyExc_TypeError,
8846 "separator: expected str instance,"
8847 " %.80s found",
8848 Py_TYPE(separator)->tp_name);
8849 goto onError;
8850 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008851 if (PyUnicode_READY(separator))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008852 goto onError;
8853 sep = separator;
8854 seplen = PyUnicode_GET_LENGTH(separator);
8855 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
8856 /* inc refcount to keep this code path symetric with the
8857 above case of a blank separator */
8858 Py_INCREF(sep);
Tim Peters05eba1f2004-08-27 21:32:02 +00008859 }
8860 }
8861
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008862 /* There are at least two things to join, or else we have a subclass
8863 * of str in the sequence.
8864 * Do a pre-pass to figure out the total amount of space we'll
8865 * need (sz), and see whether all argument are strings.
8866 */
8867 sz = 0;
8868 for (i = 0; i < seqlen; i++) {
8869 const Py_ssize_t old_sz = sz;
8870 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00008871 if (!PyUnicode_Check(item)) {
8872 PyErr_Format(PyExc_TypeError,
8873 "sequence item %zd: expected str instance,"
8874 " %.80s found",
8875 i, Py_TYPE(item)->tp_name);
8876 goto onError;
8877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878 if (PyUnicode_READY(item) == -1)
8879 goto onError;
8880 sz += PyUnicode_GET_LENGTH(item);
8881 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
8882 if (item_maxchar > maxchar)
8883 maxchar = item_maxchar;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008884 if (i != 0)
8885 sz += seplen;
8886 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
8887 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008889 goto onError;
8890 }
8891 }
Tim Petersced69f82003-09-16 20:30:58 +00008892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008893 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008894 if (res == NULL)
8895 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00008896
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008897 /* Catenate everything. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00008899 Py_ssize_t itemlen;
8900 item = items[i];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 itemlen = PyUnicode_GET_LENGTH(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008902 /* Copy item, and maybe the separator. */
8903 if (i) {
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008904 if (PyUnicode_CopyCharacters(res, res_offset,
8905 sep, 0, seplen) < 0)
8906 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907 res_offset += seplen;
Benjamin Peterson29060642009-01-31 22:14:21 +00008908 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008909 if (PyUnicode_CopyCharacters(res, res_offset,
8910 item, 0, itemlen) < 0)
8911 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008912 res_offset += itemlen;
Tim Peters05eba1f2004-08-27 21:32:02 +00008913 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008914 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00008915
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 Done:
Tim Peters05eba1f2004-08-27 21:32:02 +00008917 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008918 Py_XDECREF(sep);
8919 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008920
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00008922 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008923 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00008924 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008925 return NULL;
8926}
8927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008928#define FILL(kind, data, value, start, length) \
8929 do { \
8930 Py_ssize_t i_ = 0; \
8931 assert(kind != PyUnicode_WCHAR_KIND); \
8932 switch ((kind)) { \
8933 case PyUnicode_1BYTE_KIND: { \
8934 unsigned char * to_ = (unsigned char *)((data)) + (start); \
8935 memset(to_, (unsigned char)value, length); \
8936 break; \
8937 } \
8938 case PyUnicode_2BYTE_KIND: { \
8939 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
8940 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8941 break; \
8942 } \
8943 default: { \
8944 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
8945 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
8946 break; \
8947 } \
8948 } \
8949 } while (0)
8950
Alexander Belopolsky40018472011-02-26 01:02:56 +00008951static PyUnicodeObject *
8952pad(PyUnicodeObject *self,
8953 Py_ssize_t left,
8954 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008955 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008956{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008957 PyObject *u;
8958 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008959 int kind;
8960 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961
8962 if (left < 0)
8963 left = 0;
8964 if (right < 0)
8965 right = 0;
8966
Tim Peters7a29bd52001-09-12 03:03:31 +00008967 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00008968 Py_INCREF(self);
8969 return self;
8970 }
8971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008972 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
8973 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00008974 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
8975 return NULL;
8976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008977 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
8978 if (fill > maxchar)
8979 maxchar = fill;
8980 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008981 if (!u)
8982 return NULL;
8983
8984 kind = PyUnicode_KIND(u);
8985 data = PyUnicode_DATA(u);
8986 if (left)
8987 FILL(kind, data, fill, 0, left);
8988 if (right)
8989 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinner157f83f2011-09-28 21:41:31 +02008990 if (PyUnicode_CopyCharacters(u, left,
8991 (PyObject*)self, 0,
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008992 _PyUnicode_LENGTH(self)) < 0)
8993 {
8994 Py_DECREF(u);
8995 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008996 }
8997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008998 return (PyUnicodeObject*)u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008999}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009001
Alexander Belopolsky40018472011-02-26 01:02:56 +00009002PyObject *
9003PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009004{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009005 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006
9007 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009008 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 switch(PyUnicode_KIND(string)) {
9012 case PyUnicode_1BYTE_KIND:
9013 list = ucs1lib_splitlines(
9014 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9015 PyUnicode_GET_LENGTH(string), keepends);
9016 break;
9017 case PyUnicode_2BYTE_KIND:
9018 list = ucs2lib_splitlines(
9019 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9020 PyUnicode_GET_LENGTH(string), keepends);
9021 break;
9022 case PyUnicode_4BYTE_KIND:
9023 list = ucs4lib_splitlines(
9024 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9025 PyUnicode_GET_LENGTH(string), keepends);
9026 break;
9027 default:
9028 assert(0);
9029 list = 0;
9030 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009031 Py_DECREF(string);
9032 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033}
9034
Alexander Belopolsky40018472011-02-26 01:02:56 +00009035static PyObject *
9036split(PyUnicodeObject *self,
9037 PyUnicodeObject *substring,
9038 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 int kind1, kind2, kind;
9041 void *buf1, *buf2;
9042 Py_ssize_t len1, len2;
9043 PyObject* out;
9044
Guido van Rossumd57fd912000-03-10 22:53:23 +00009045 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009046 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048 if (PyUnicode_READY(self) == -1)
9049 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 if (substring == NULL)
9052 switch(PyUnicode_KIND(self)) {
9053 case PyUnicode_1BYTE_KIND:
9054 return ucs1lib_split_whitespace(
9055 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9056 PyUnicode_GET_LENGTH(self), maxcount
9057 );
9058 case PyUnicode_2BYTE_KIND:
9059 return ucs2lib_split_whitespace(
9060 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9061 PyUnicode_GET_LENGTH(self), maxcount
9062 );
9063 case PyUnicode_4BYTE_KIND:
9064 return ucs4lib_split_whitespace(
9065 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9066 PyUnicode_GET_LENGTH(self), maxcount
9067 );
9068 default:
9069 assert(0);
9070 return NULL;
9071 }
9072
9073 if (PyUnicode_READY(substring) == -1)
9074 return NULL;
9075
9076 kind1 = PyUnicode_KIND(self);
9077 kind2 = PyUnicode_KIND(substring);
9078 kind = kind1 > kind2 ? kind1 : kind2;
9079 buf1 = PyUnicode_DATA(self);
9080 buf2 = PyUnicode_DATA(substring);
9081 if (kind1 != kind)
9082 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9083 if (!buf1)
9084 return NULL;
9085 if (kind2 != kind)
9086 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9087 if (!buf2) {
9088 if (kind1 != kind) PyMem_Free(buf1);
9089 return NULL;
9090 }
9091 len1 = PyUnicode_GET_LENGTH(self);
9092 len2 = PyUnicode_GET_LENGTH(substring);
9093
9094 switch(kind) {
9095 case PyUnicode_1BYTE_KIND:
9096 out = ucs1lib_split(
9097 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9098 break;
9099 case PyUnicode_2BYTE_KIND:
9100 out = ucs2lib_split(
9101 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9102 break;
9103 case PyUnicode_4BYTE_KIND:
9104 out = ucs4lib_split(
9105 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9106 break;
9107 default:
9108 out = NULL;
9109 }
9110 if (kind1 != kind)
9111 PyMem_Free(buf1);
9112 if (kind2 != kind)
9113 PyMem_Free(buf2);
9114 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115}
9116
Alexander Belopolsky40018472011-02-26 01:02:56 +00009117static PyObject *
9118rsplit(PyUnicodeObject *self,
9119 PyUnicodeObject *substring,
9120 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009122 int kind1, kind2, kind;
9123 void *buf1, *buf2;
9124 Py_ssize_t len1, len2;
9125 PyObject* out;
9126
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009127 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009128 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 if (PyUnicode_READY(self) == -1)
9131 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 if (substring == NULL)
9134 switch(PyUnicode_KIND(self)) {
9135 case PyUnicode_1BYTE_KIND:
9136 return ucs1lib_rsplit_whitespace(
9137 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9138 PyUnicode_GET_LENGTH(self), maxcount
9139 );
9140 case PyUnicode_2BYTE_KIND:
9141 return ucs2lib_rsplit_whitespace(
9142 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9143 PyUnicode_GET_LENGTH(self), maxcount
9144 );
9145 case PyUnicode_4BYTE_KIND:
9146 return ucs4lib_rsplit_whitespace(
9147 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9148 PyUnicode_GET_LENGTH(self), maxcount
9149 );
9150 default:
9151 assert(0);
9152 return NULL;
9153 }
9154
9155 if (PyUnicode_READY(substring) == -1)
9156 return NULL;
9157
9158 kind1 = PyUnicode_KIND(self);
9159 kind2 = PyUnicode_KIND(substring);
9160 kind = kind1 > kind2 ? kind1 : kind2;
9161 buf1 = PyUnicode_DATA(self);
9162 buf2 = PyUnicode_DATA(substring);
9163 if (kind1 != kind)
9164 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9165 if (!buf1)
9166 return NULL;
9167 if (kind2 != kind)
9168 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9169 if (!buf2) {
9170 if (kind1 != kind) PyMem_Free(buf1);
9171 return NULL;
9172 }
9173 len1 = PyUnicode_GET_LENGTH(self);
9174 len2 = PyUnicode_GET_LENGTH(substring);
9175
9176 switch(kind) {
9177 case PyUnicode_1BYTE_KIND:
9178 out = ucs1lib_rsplit(
9179 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9180 break;
9181 case PyUnicode_2BYTE_KIND:
9182 out = ucs2lib_rsplit(
9183 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9184 break;
9185 case PyUnicode_4BYTE_KIND:
9186 out = ucs4lib_rsplit(
9187 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9188 break;
9189 default:
9190 out = NULL;
9191 }
9192 if (kind1 != kind)
9193 PyMem_Free(buf1);
9194 if (kind2 != kind)
9195 PyMem_Free(buf2);
9196 return out;
9197}
9198
9199static Py_ssize_t
9200anylib_find(int kind, void *buf1, Py_ssize_t len1,
9201 void *buf2, Py_ssize_t len2, Py_ssize_t offset)
9202{
9203 switch(kind) {
9204 case PyUnicode_1BYTE_KIND:
9205 return ucs1lib_find(buf1, len1, buf2, len2, offset);
9206 case PyUnicode_2BYTE_KIND:
9207 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9208 case PyUnicode_4BYTE_KIND:
9209 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9210 }
9211 assert(0);
9212 return -1;
9213}
9214
9215static Py_ssize_t
9216anylib_count(int kind, void* sbuf, Py_ssize_t slen,
9217 void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
9218{
9219 switch(kind) {
9220 case PyUnicode_1BYTE_KIND:
9221 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
9222 case PyUnicode_2BYTE_KIND:
9223 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9224 case PyUnicode_4BYTE_KIND:
9225 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9226 }
9227 assert(0);
9228 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009229}
9230
Alexander Belopolsky40018472011-02-26 01:02:56 +00009231static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232replace(PyObject *self, PyObject *str1,
9233 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 PyObject *u;
9236 char *sbuf = PyUnicode_DATA(self);
9237 char *buf1 = PyUnicode_DATA(str1);
9238 char *buf2 = PyUnicode_DATA(str2);
9239 int srelease = 0, release1 = 0, release2 = 0;
9240 int skind = PyUnicode_KIND(self);
9241 int kind1 = PyUnicode_KIND(str1);
9242 int kind2 = PyUnicode_KIND(str2);
9243 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9244 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9245 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246
9247 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009248 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009250 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 if (skind < kind1)
9253 /* substring too wide to be present */
9254 goto nothing;
9255
9256 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009257 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009258 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009260 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009261 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009262 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 Py_UCS4 u1, u2, maxchar;
9264 int mayshrink, rkind;
9265 u1 = PyUnicode_READ_CHAR(str1, 0);
9266 if (!findchar(sbuf, PyUnicode_KIND(self),
9267 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009268 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 u2 = PyUnicode_READ_CHAR(str2, 0);
9270 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9271 /* Replacing u1 with u2 may cause a maxchar reduction in the
9272 result string. */
9273 mayshrink = maxchar > 127;
9274 if (u2 > maxchar) {
9275 maxchar = u2;
9276 mayshrink = 0;
9277 }
9278 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009279 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 goto error;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009281 if (PyUnicode_CopyCharacters(u, 0,
9282 (PyObject*)self, 0, slen) < 0)
9283 {
9284 Py_DECREF(u);
9285 return NULL;
9286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 rkind = PyUnicode_KIND(u);
9288 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9289 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009290 if (--maxcount < 0)
9291 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 if (mayshrink) {
9295 PyObject *tmp = u;
9296 u = PyUnicode_FromKindAndData(rkind, PyUnicode_DATA(tmp),
9297 PyUnicode_GET_LENGTH(tmp));
9298 Py_DECREF(tmp);
9299 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 int rkind = skind;
9302 char *res;
9303 if (kind1 < rkind) {
9304 /* widen substring */
9305 buf1 = _PyUnicode_AsKind(str1, rkind);
9306 if (!buf1) goto error;
9307 release1 = 1;
9308 }
9309 i = anylib_find(rkind, sbuf, slen, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009310 if (i < 0)
9311 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 if (rkind > kind2) {
9313 /* widen replacement */
9314 buf2 = _PyUnicode_AsKind(str2, rkind);
9315 if (!buf2) goto error;
9316 release2 = 1;
9317 }
9318 else if (rkind < kind2) {
9319 /* widen self and buf1 */
9320 rkind = kind2;
9321 if (release1) PyMem_Free(buf1);
9322 sbuf = _PyUnicode_AsKind(self, rkind);
9323 if (!sbuf) goto error;
9324 srelease = 1;
9325 buf1 = _PyUnicode_AsKind(str1, rkind);
9326 if (!buf1) goto error;
9327 release1 = 1;
9328 }
9329 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, slen));
9330 if (!res) {
9331 PyErr_NoMemory();
9332 goto error;
9333 }
9334 memcpy(res, sbuf, PyUnicode_KIND_SIZE(rkind, slen));
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009335 /* change everything in-place, starting with this one */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9337 buf2,
9338 PyUnicode_KIND_SIZE(rkind, len2));
9339 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009340
9341 while ( --maxcount > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 i = anylib_find(rkind, sbuf+PyUnicode_KIND_SIZE(rkind, i),
9343 slen-i,
9344 buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009345 if (i == -1)
9346 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 memcpy(res + PyUnicode_KIND_SIZE(rkind, i),
9348 buf2,
9349 PyUnicode_KIND_SIZE(rkind, len2));
9350 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009352
9353 u = PyUnicode_FromKindAndData(rkind, res, slen);
9354 PyMem_Free(res);
9355 if (!u) goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 Py_ssize_t n, i, j, ires;
9360 Py_ssize_t product, new_size;
9361 int rkind = skind;
9362 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364 if (kind1 < rkind) {
9365 buf1 = _PyUnicode_AsKind(str1, rkind);
9366 if (!buf1) goto error;
9367 release1 = 1;
9368 }
9369 n = anylib_count(rkind, sbuf, slen, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009370 if (n == 0)
9371 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009372 if (kind2 < rkind) {
9373 buf2 = _PyUnicode_AsKind(str2, rkind);
9374 if (!buf2) goto error;
9375 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 else if (kind2 > rkind) {
9378 rkind = kind2;
9379 sbuf = _PyUnicode_AsKind(self, rkind);
9380 if (!sbuf) goto error;
9381 srelease = 1;
9382 if (release1) PyMem_Free(buf1);
9383 buf1 = _PyUnicode_AsKind(str1, rkind);
9384 if (!buf1) goto error;
9385 release1 = 1;
9386 }
9387 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9388 PyUnicode_GET_LENGTH(str1))); */
9389 product = n * (len2-len1);
9390 if ((product / (len2-len1)) != n) {
9391 PyErr_SetString(PyExc_OverflowError,
9392 "replace string is too long");
9393 goto error;
9394 }
9395 new_size = slen + product;
9396 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9397 PyErr_SetString(PyExc_OverflowError,
9398 "replace string is too long");
9399 goto error;
9400 }
9401 res = PyMem_Malloc(PyUnicode_KIND_SIZE(rkind, new_size));
9402 if (!res)
9403 goto error;
9404 ires = i = 0;
9405 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009406 while (n-- > 0) {
9407 /* look for next match */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 j = anylib_find(rkind,
9409 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9410 slen-i, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009411 if (j == -1)
9412 break;
9413 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009414 /* copy unchanged part [i:j] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9416 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9417 PyUnicode_KIND_SIZE(rkind, j-i));
9418 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009419 }
9420 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 if (len2 > 0) {
9422 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9423 buf2,
9424 PyUnicode_KIND_SIZE(rkind, len2));
9425 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009430 /* copy tail [i:] */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9432 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9433 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009434 } else {
9435 /* interleave */
9436 while (n > 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9438 buf2,
9439 PyUnicode_KIND_SIZE(rkind, len2));
9440 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009441 if (--n <= 0)
9442 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9444 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9445 PyUnicode_KIND_SIZE(rkind, 1));
9446 ires++;
9447 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 memcpy(res + PyUnicode_KIND_SIZE(rkind, ires),
9450 sbuf + PyUnicode_KIND_SIZE(rkind, i),
9451 PyUnicode_KIND_SIZE(rkind, slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009452 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453 u = PyUnicode_FromKindAndData(rkind, res, new_size);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02009454 PyMem_Free(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 if (srelease)
9457 PyMem_FREE(sbuf);
9458 if (release1)
9459 PyMem_FREE(buf1);
9460 if (release2)
9461 PyMem_FREE(buf2);
9462 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009463
Benjamin Peterson29060642009-01-31 22:14:21 +00009464 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009465 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 if (srelease)
9467 PyMem_FREE(sbuf);
9468 if (release1)
9469 PyMem_FREE(buf1);
9470 if (release2)
9471 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009472 if (PyUnicode_CheckExact(self)) {
9473 Py_INCREF(self);
9474 return (PyObject *) self;
9475 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009476 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 error:
9478 if (srelease && sbuf)
9479 PyMem_FREE(sbuf);
9480 if (release1 && buf1)
9481 PyMem_FREE(buf1);
9482 if (release2 && buf2)
9483 PyMem_FREE(buf2);
9484 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485}
9486
9487/* --- Unicode Object Methods --------------------------------------------- */
9488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009489PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009490 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491\n\
9492Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009493characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494
9495static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009496unicode_title(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498 return fixup(self, fixtitle);
9499}
9500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009501PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503\n\
9504Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009505have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506
9507static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009508unicode_capitalize(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 return fixup(self, fixcapitalize);
9511}
9512
9513#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009514PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009515 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516\n\
9517Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009518normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009519
9520static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009521unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522{
9523 PyObject *list;
9524 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009525 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527 /* Split into words */
9528 list = split(self, NULL, -1);
9529 if (!list)
9530 return NULL;
9531
9532 /* Capitalize each word */
9533 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9534 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009535 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009536 if (item == NULL)
9537 goto onError;
9538 Py_DECREF(PyList_GET_ITEM(list, i));
9539 PyList_SET_ITEM(list, i, item);
9540 }
9541
9542 /* Join the words to form a new string */
9543 item = PyUnicode_Join(NULL, list);
9544
Benjamin Peterson29060642009-01-31 22:14:21 +00009545 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546 Py_DECREF(list);
9547 return (PyObject *)item;
9548}
9549#endif
9550
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009551/* Argument converter. Coerces to a single unicode character */
9552
9553static int
9554convert_uc(PyObject *obj, void *addr)
9555{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009557 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009558
Benjamin Peterson14339b62009-01-31 16:36:08 +00009559 uniobj = PyUnicode_FromObject(obj);
9560 if (uniobj == NULL) {
9561 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009562 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009563 return 0;
9564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009566 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009567 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +00009568 Py_DECREF(uniobj);
9569 return 0;
9570 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009572 Py_DECREF(uniobj);
9573 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009574}
9575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009576PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009577 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +00009579Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009580done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009581
9582static PyObject *
9583unicode_center(PyUnicodeObject *self, PyObject *args)
9584{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009585 Py_ssize_t marg, left;
9586 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 Py_UCS4 fillchar = ' ';
9588
Victor Stinnere9a29352011-10-01 02:14:59 +02009589 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591
Victor Stinnere9a29352011-10-01 02:14:59 +02009592 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593 return NULL;
9594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009595 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596 Py_INCREF(self);
9597 return (PyObject*) self;
9598 }
9599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601 left = marg / 2 + (marg & width & 1);
9602
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00009603 return (PyObject*) pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604}
9605
Marc-André Lemburge5034372000-08-08 08:04:29 +00009606#if 0
9607
9608/* This code should go into some future Unicode collation support
9609 module. The basic comparison should compare ordinals on a naive
Georg Brandlc6c31782009-06-08 13:41:29 +00009610 basis (this is what Java does and thus Jython too). */
Marc-André Lemburge5034372000-08-08 08:04:29 +00009611
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009612/* speedy UTF-16 code point order comparison */
9613/* gleaned from: */
9614/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
9615
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009616static short utf16Fixup[32] =
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009617{
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009618 0, 0, 0, 0, 0, 0, 0, 0,
Tim Petersced69f82003-09-16 20:30:58 +00009619 0, 0, 0, 0, 0, 0, 0, 0,
9620 0, 0, 0, 0, 0, 0, 0, 0,
Marc-André Lemburge12896e2000-07-07 17:51:08 +00009621 0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009622};
9623
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624static int
9625unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9626{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009627 Py_ssize_t len1, len2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009628
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629 Py_UNICODE *s1 = str1->str;
9630 Py_UNICODE *s2 = str2->str;
9631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632 len1 = str1->_base._base.length;
9633 len2 = str2->_base._base.length;
Tim Petersced69f82003-09-16 20:30:58 +00009634
Guido van Rossumd57fd912000-03-10 22:53:23 +00009635 while (len1 > 0 && len2 > 0) {
Tim Petersced69f82003-09-16 20:30:58 +00009636 Py_UNICODE c1, c2;
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009637
9638 c1 = *s1++;
9639 c2 = *s2++;
Fredrik Lundh45714e92001-06-26 16:39:36 +00009640
Benjamin Peterson29060642009-01-31 22:14:21 +00009641 if (c1 > (1<<11) * 26)
9642 c1 += utf16Fixup[c1>>11];
9643 if (c2 > (1<<11) * 26)
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009644 c2 += utf16Fixup[c2>>11];
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009645 /* now c1 and c2 are in UTF-32-compatible order */
Fredrik Lundh45714e92001-06-26 16:39:36 +00009646
9647 if (c1 != c2)
9648 return (c1 < c2) ? -1 : 1;
Tim Petersced69f82003-09-16 20:30:58 +00009649
Marc-André Lemburg1e7205a2000-07-04 09:51:07 +00009650 len1--; len2--;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009651 }
9652
9653 return (len1 < len2) ? -1 : (len1 != len2);
9654}
9655
Marc-André Lemburge5034372000-08-08 08:04:29 +00009656#else
9657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658/* This function assumes that str1 and str2 are readied by the caller. */
9659
Marc-André Lemburge5034372000-08-08 08:04:29 +00009660static int
9661unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
9662{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 int kind1, kind2;
9664 void *data1, *data2;
9665 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009667 kind1 = PyUnicode_KIND(str1);
9668 kind2 = PyUnicode_KIND(str2);
9669 data1 = PyUnicode_DATA(str1);
9670 data2 = PyUnicode_DATA(str2);
9671 len1 = PyUnicode_GET_LENGTH(str1);
9672 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +00009673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009674 for (i = 0; i < len1 && i < len2; ++i) {
9675 Py_UCS4 c1, c2;
9676 c1 = PyUnicode_READ(kind1, data1, i);
9677 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +00009678
9679 if (c1 != c2)
9680 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +00009681 }
9682
9683 return (len1 < len2) ? -1 : (len1 != len2);
9684}
9685
9686#endif
9687
Alexander Belopolsky40018472011-02-26 01:02:56 +00009688int
9689PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9692 if (PyUnicode_READY(left) == -1 ||
9693 PyUnicode_READY(right) == -1)
9694 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009695 return unicode_compare((PyUnicodeObject *)left,
9696 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +00009698 PyErr_Format(PyExc_TypeError,
9699 "Can't compare %.100s and %.100s",
9700 left->ob_type->tp_name,
9701 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009702 return -1;
9703}
9704
Martin v. Löwis5b222132007-06-10 09:51:05 +00009705int
9706PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
9707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 Py_ssize_t i;
9709 int kind;
9710 void *data;
9711 Py_UCS4 chr;
9712
Victor Stinner910337b2011-10-03 03:20:16 +02009713 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 if (PyUnicode_READY(uni) == -1)
9715 return -1;
9716 kind = PyUnicode_KIND(uni);
9717 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +00009718 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
9720 if (chr != str[i])
9721 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +00009722 /* This check keeps Python strings that end in '\0' from comparing equal
9723 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +00009725 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009726 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +00009727 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +00009728 return 0;
9729}
9730
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009731
Benjamin Peterson29060642009-01-31 22:14:21 +00009732#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +00009733 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009734
Alexander Belopolsky40018472011-02-26 01:02:56 +00009735PyObject *
9736PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009737{
9738 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009739
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009740 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
9741 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009742 if (PyUnicode_READY(left) == -1 ||
9743 PyUnicode_READY(right) == -1)
9744 return NULL;
9745 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
9746 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009747 if (op == Py_EQ) {
9748 Py_INCREF(Py_False);
9749 return Py_False;
9750 }
9751 if (op == Py_NE) {
9752 Py_INCREF(Py_True);
9753 return Py_True;
9754 }
9755 }
9756 if (left == right)
9757 result = 0;
9758 else
9759 result = unicode_compare((PyUnicodeObject *)left,
9760 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +00009761
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00009762 /* Convert the return value to a Boolean */
9763 switch (op) {
9764 case Py_EQ:
9765 v = TEST_COND(result == 0);
9766 break;
9767 case Py_NE:
9768 v = TEST_COND(result != 0);
9769 break;
9770 case Py_LE:
9771 v = TEST_COND(result <= 0);
9772 break;
9773 case Py_GE:
9774 v = TEST_COND(result >= 0);
9775 break;
9776 case Py_LT:
9777 v = TEST_COND(result == -1);
9778 break;
9779 case Py_GT:
9780 v = TEST_COND(result == 1);
9781 break;
9782 default:
9783 PyErr_BadArgument();
9784 return NULL;
9785 }
9786 Py_INCREF(v);
9787 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009788 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00009789
Brian Curtindfc80e32011-08-10 20:28:54 -05009790 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00009791}
9792
Alexander Belopolsky40018472011-02-26 01:02:56 +00009793int
9794PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +00009795{
Thomas Wouters477c8d52006-05-27 19:21:47 +00009796 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 int kind1, kind2, kind;
9798 void *buf1, *buf2;
9799 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009800 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009801
9802 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +00009803 sub = PyUnicode_FromObject(element);
9804 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009805 PyErr_Format(PyExc_TypeError,
9806 "'in <string>' requires string as left operand, not %s",
9807 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009808 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009809 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 if (PyUnicode_READY(sub) == -1)
9811 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009812
Thomas Wouters477c8d52006-05-27 19:21:47 +00009813 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +02009814 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009815 Py_DECREF(sub);
9816 return -1;
9817 }
9818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009819 kind1 = PyUnicode_KIND(str);
9820 kind2 = PyUnicode_KIND(sub);
9821 kind = kind1 > kind2 ? kind1 : kind2;
9822 buf1 = PyUnicode_DATA(str);
9823 buf2 = PyUnicode_DATA(sub);
9824 if (kind1 != kind)
9825 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
9826 if (!buf1) {
9827 Py_DECREF(sub);
9828 return -1;
9829 }
9830 if (kind2 != kind)
9831 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
9832 if (!buf2) {
9833 Py_DECREF(sub);
9834 if (kind1 != kind) PyMem_Free(buf1);
9835 return -1;
9836 }
9837 len1 = PyUnicode_GET_LENGTH(str);
9838 len2 = PyUnicode_GET_LENGTH(sub);
9839
9840 switch(kind) {
9841 case PyUnicode_1BYTE_KIND:
9842 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
9843 break;
9844 case PyUnicode_2BYTE_KIND:
9845 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
9846 break;
9847 case PyUnicode_4BYTE_KIND:
9848 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
9849 break;
9850 default:
9851 result = -1;
9852 assert(0);
9853 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009854
9855 Py_DECREF(str);
9856 Py_DECREF(sub);
9857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009858 if (kind1 != kind)
9859 PyMem_Free(buf1);
9860 if (kind2 != kind)
9861 PyMem_Free(buf2);
9862
Guido van Rossum403d68b2000-03-13 15:55:09 +00009863 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +00009864}
9865
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866/* Concat to string or Unicode object giving a new Unicode object. */
9867
Alexander Belopolsky40018472011-02-26 01:02:56 +00009868PyObject *
9869PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 PyObject *u = NULL, *v = NULL, *w;
9872 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009873
9874 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009877 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009878 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009879 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009880 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009881
9882 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +02009883 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009884 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886 }
Victor Stinnera464fc12011-10-02 20:39:30 +02009887 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009888 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009890 }
9891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +02009893 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009894
Guido van Rossumd57fd912000-03-10 22:53:23 +00009895 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896 w = PyUnicode_New(
9897 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
9898 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009900 goto onError;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009901 if (PyUnicode_CopyCharacters(w, 0, u, 0, PyUnicode_GET_LENGTH(u)) < 0)
9902 goto onError;
Victor Stinner157f83f2011-09-28 21:41:31 +02009903 if (PyUnicode_CopyCharacters(w, PyUnicode_GET_LENGTH(u),
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009904 v, 0,
9905 PyUnicode_GET_LENGTH(v)) < 0)
9906 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907 Py_DECREF(u);
9908 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910
Benjamin Peterson29060642009-01-31 22:14:21 +00009911 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00009912 Py_XDECREF(u);
9913 Py_XDECREF(v);
9914 return NULL;
9915}
9916
Walter Dörwald1ab83302007-05-18 17:15:44 +00009917void
Victor Stinner23e56682011-10-03 03:54:37 +02009918PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +00009919{
Victor Stinner23e56682011-10-03 03:54:37 +02009920 PyObject *left, *res;
9921
9922 if (p_left == NULL) {
9923 if (!PyErr_Occurred())
9924 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +00009925 return;
9926 }
Victor Stinner23e56682011-10-03 03:54:37 +02009927 left = *p_left;
9928 if (right == NULL || !PyUnicode_Check(left)) {
9929 if (!PyErr_Occurred())
9930 PyErr_BadInternalCall();
9931 goto error;
9932 }
9933
9934 if (PyUnicode_CheckExact(left) && left != unicode_empty
9935 && PyUnicode_CheckExact(right) && right != unicode_empty
9936 && unicode_resizable(left)
9937 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
9938 || _PyUnicode_WSTR(left) != NULL))
9939 {
9940 Py_ssize_t u_len, v_len, new_len, copied;
9941
9942 /* FIXME: don't make wstr string ready */
9943 if (PyUnicode_READY(left))
9944 goto error;
9945 if (PyUnicode_READY(right))
9946 goto error;
9947
9948 /* FIXME: support ascii+latin1, PyASCIIObject => PyCompactUnicodeObject */
9949 if (PyUnicode_MAX_CHAR_VALUE(right) <= PyUnicode_MAX_CHAR_VALUE(left))
9950 {
9951 u_len = PyUnicode_GET_LENGTH(left);
9952 v_len = PyUnicode_GET_LENGTH(right);
9953 if (u_len > PY_SSIZE_T_MAX - v_len) {
9954 PyErr_SetString(PyExc_OverflowError,
9955 "strings are too large to concat");
9956 goto error;
9957 }
9958 new_len = u_len + v_len;
9959
9960 /* Now we own the last reference to 'left', so we can resize it
9961 * in-place.
9962 */
9963 if (unicode_resize(&left, new_len) != 0) {
9964 /* XXX if _PyUnicode_Resize() fails, 'left' has been
9965 * deallocated so it cannot be put back into
9966 * 'variable'. The MemoryError is raised when there
9967 * is no value in 'variable', which might (very
9968 * remotely) be a cause of incompatibilities.
9969 */
9970 goto error;
9971 }
9972 /* copy 'right' into the newly allocated area of 'left' */
9973 copied = PyUnicode_CopyCharacters(left, u_len,
9974 right, 0,
9975 v_len);
9976 assert(0 <= copied);
9977 *p_left = left;
9978 return;
9979 }
9980 }
9981
9982 res = PyUnicode_Concat(left, right);
9983 if (res == NULL)
9984 goto error;
9985 Py_DECREF(left);
9986 *p_left = res;
9987 return;
9988
9989error:
9990 Py_DECREF(*p_left);
9991 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00009992}
9993
9994void
9995PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
9996{
Benjamin Peterson14339b62009-01-31 16:36:08 +00009997 PyUnicode_Append(pleft, right);
9998 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +00009999}
10000
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010001PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010002 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010004Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010005string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010006interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010007
10008static PyObject *
10009unicode_count(PyUnicodeObject *self, PyObject *args)
10010{
10011 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010012 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010013 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 int kind1, kind2, kind;
10016 void *buf1, *buf2;
10017 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010018
Jesus Ceaac451502011-04-20 17:09:23 +020010019 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10020 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010021 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 kind1 = PyUnicode_KIND(self);
10024 kind2 = PyUnicode_KIND(substring);
10025 kind = kind1 > kind2 ? kind1 : kind2;
10026 buf1 = PyUnicode_DATA(self);
10027 buf2 = PyUnicode_DATA(substring);
10028 if (kind1 != kind)
10029 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10030 if (!buf1) {
10031 Py_DECREF(substring);
10032 return NULL;
10033 }
10034 if (kind2 != kind)
10035 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10036 if (!buf2) {
10037 Py_DECREF(substring);
10038 if (kind1 != kind) PyMem_Free(buf1);
10039 return NULL;
10040 }
10041 len1 = PyUnicode_GET_LENGTH(self);
10042 len2 = PyUnicode_GET_LENGTH(substring);
10043
10044 ADJUST_INDICES(start, end, len1);
10045 switch(kind) {
10046 case PyUnicode_1BYTE_KIND:
10047 iresult = ucs1lib_count(
10048 ((Py_UCS1*)buf1) + start, end - start,
10049 buf2, len2, PY_SSIZE_T_MAX
10050 );
10051 break;
10052 case PyUnicode_2BYTE_KIND:
10053 iresult = ucs2lib_count(
10054 ((Py_UCS2*)buf1) + start, end - start,
10055 buf2, len2, PY_SSIZE_T_MAX
10056 );
10057 break;
10058 case PyUnicode_4BYTE_KIND:
10059 iresult = ucs4lib_count(
10060 ((Py_UCS4*)buf1) + start, end - start,
10061 buf2, len2, PY_SSIZE_T_MAX
10062 );
10063 break;
10064 default:
10065 assert(0); iresult = 0;
10066 }
10067
10068 result = PyLong_FromSsize_t(iresult);
10069
10070 if (kind1 != kind)
10071 PyMem_Free(buf1);
10072 if (kind2 != kind)
10073 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010074
10075 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010076
Guido van Rossumd57fd912000-03-10 22:53:23 +000010077 return result;
10078}
10079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010080PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010081 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010083Encode S using the codec registered for encoding. Default encoding\n\
10084is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010085handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010086a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10087'xmlcharrefreplace' as well as any other name registered with\n\
10088codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010089
10090static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010091unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010093 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010094 char *encoding = NULL;
10095 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010096
Benjamin Peterson308d6372009-09-18 21:42:35 +000010097 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10098 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010099 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010100 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010101}
10102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010103PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010104 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010105\n\
10106Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010107If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108
10109static PyObject*
10110unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10111{
10112 Py_UNICODE *e;
10113 Py_UNICODE *p;
10114 Py_UNICODE *q;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010115 Py_UNICODE *qe;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 Py_ssize_t i, j, incr, wstr_length;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010117 PyUnicodeObject *u;
10118 int tabsize = 8;
10119
10120 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 if (PyUnicode_AsUnicodeAndSize((PyObject *)self, &wstr_length) == NULL)
10124 return NULL;
10125
Thomas Wouters7e474022000-07-16 12:04:32 +000010126 /* First pass: determine size of output string */
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010127 i = 0; /* chars up to and including most recent \n or \r */
10128 j = 0; /* chars since most recent \n or \r (use in tab calculations) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010129 e = _PyUnicode_WSTR(self) + wstr_length; /* end of input */
10130 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010131 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010132 if (tabsize > 0) {
10133 incr = tabsize - (j % tabsize); /* cannot overflow */
10134 if (j > PY_SSIZE_T_MAX - incr)
10135 goto overflow1;
10136 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010137 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010138 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010139 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010140 if (j > PY_SSIZE_T_MAX - 1)
10141 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010142 j++;
10143 if (*p == '\n' || *p == '\r') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010144 if (i > PY_SSIZE_T_MAX - j)
10145 goto overflow1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010146 i += j;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010147 j = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148 }
10149 }
10150
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010151 if (i > PY_SSIZE_T_MAX - j)
Benjamin Peterson29060642009-01-31 22:14:21 +000010152 goto overflow1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010153
Guido van Rossumd57fd912000-03-10 22:53:23 +000010154 /* Second pass: create output string and fill it */
10155 u = _PyUnicode_New(i + j);
10156 if (!u)
10157 return NULL;
10158
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010159 j = 0; /* same as in first pass */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 q = _PyUnicode_WSTR(u); /* next output char */
10161 qe = _PyUnicode_WSTR(u) + PyUnicode_GET_SIZE(u); /* end of output */
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 for (p = _PyUnicode_WSTR(self); p < e; p++)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010164 if (*p == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010165 if (tabsize > 0) {
10166 i = tabsize - (j % tabsize);
10167 j += i;
10168 while (i--) {
10169 if (q >= qe)
10170 goto overflow2;
10171 *q++ = ' ';
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010172 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010174 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010175 else {
10176 if (q >= qe)
10177 goto overflow2;
10178 *q++ = *p;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010179 j++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010180 if (*p == '\n' || *p == '\r')
10181 j = 0;
10182 }
10183
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020010184 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 Py_DECREF(u);
10186 return NULL;
10187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010188 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010189
10190 overflow2:
10191 Py_DECREF(u);
10192 overflow1:
10193 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10194 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010195}
10196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010197PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010198 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010199\n\
10200Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010201such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010202arguments start and end are interpreted as in slice notation.\n\
10203\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010204Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010205
10206static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208{
Jesus Ceaac451502011-04-20 17:09:23 +020010209 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010210 Py_ssize_t start;
10211 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010212 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010213
Jesus Ceaac451502011-04-20 17:09:23 +020010214 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10215 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010216 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 if (PyUnicode_READY(self) == -1)
10219 return NULL;
10220 if (PyUnicode_READY(substring) == -1)
10221 return NULL;
10222
10223 result = any_find_slice(
10224 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10225 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010227
10228 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 if (result == -2)
10231 return NULL;
10232
Christian Heimes217cfd12007-12-02 14:31:20 +000010233 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010234}
10235
10236static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010237unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010239 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10240 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010243}
10244
Guido van Rossumc2504932007-09-18 19:42:40 +000010245/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010246 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010247static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010248unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010249{
Guido van Rossumc2504932007-09-18 19:42:40 +000010250 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010251 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 if (_PyUnicode_HASH(self) != -1)
10254 return _PyUnicode_HASH(self);
10255 if (PyUnicode_READY(self) == -1)
10256 return -1;
10257 len = PyUnicode_GET_LENGTH(self);
10258
10259 /* The hash function as a macro, gets expanded three times below. */
10260#define HASH(P) \
10261 x = (Py_uhash_t)*P << 7; \
10262 while (--len >= 0) \
10263 x = (1000003*x) ^ (Py_uhash_t)*P++;
10264
10265 switch (PyUnicode_KIND(self)) {
10266 case PyUnicode_1BYTE_KIND: {
10267 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10268 HASH(c);
10269 break;
10270 }
10271 case PyUnicode_2BYTE_KIND: {
10272 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10273 HASH(s);
10274 break;
10275 }
10276 default: {
10277 Py_UCS4 *l;
10278 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10279 "Impossible switch case in unicode_hash");
10280 l = PyUnicode_4BYTE_DATA(self);
10281 HASH(l);
10282 break;
10283 }
10284 }
10285 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10286
Guido van Rossumc2504932007-09-18 19:42:40 +000010287 if (x == -1)
10288 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010290 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010291}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010294PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010295 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010296\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010297Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298
10299static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010301{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010302 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010303 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010304 Py_ssize_t start;
10305 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306
Jesus Ceaac451502011-04-20 17:09:23 +020010307 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10308 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 if (PyUnicode_READY(self) == -1)
10312 return NULL;
10313 if (PyUnicode_READY(substring) == -1)
10314 return NULL;
10315
10316 result = any_find_slice(
10317 ucs1lib_find_slice, ucs2lib_find_slice, ucs4lib_find_slice,
10318 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320
10321 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 if (result == -2)
10324 return NULL;
10325
Guido van Rossumd57fd912000-03-10 22:53:23 +000010326 if (result < 0) {
10327 PyErr_SetString(PyExc_ValueError, "substring not found");
10328 return NULL;
10329 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010330
Christian Heimes217cfd12007-12-02 14:31:20 +000010331 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332}
10333
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010334PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010335 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010336\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010337Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010338at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010339
10340static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010341unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010342{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 Py_ssize_t i, length;
10344 int kind;
10345 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346 int cased;
10347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 if (PyUnicode_READY(self) == -1)
10349 return NULL;
10350 length = PyUnicode_GET_LENGTH(self);
10351 kind = PyUnicode_KIND(self);
10352 data = PyUnicode_DATA(self);
10353
Guido van Rossumd57fd912000-03-10 22:53:23 +000010354 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010355 if (length == 1)
10356 return PyBool_FromLong(
10357 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010359 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010361 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010362
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 for (i = 0; i < length; i++) {
10365 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010366
Benjamin Peterson29060642009-01-31 22:14:21 +000010367 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10368 return PyBool_FromLong(0);
10369 else if (!cased && Py_UNICODE_ISLOWER(ch))
10370 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010371 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010372 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373}
10374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010375PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010376 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010377\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010378Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010379at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380
10381static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010382unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010383{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 Py_ssize_t i, length;
10385 int kind;
10386 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387 int cased;
10388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 if (PyUnicode_READY(self) == -1)
10390 return NULL;
10391 length = PyUnicode_GET_LENGTH(self);
10392 kind = PyUnicode_KIND(self);
10393 data = PyUnicode_DATA(self);
10394
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 if (length == 1)
10397 return PyBool_FromLong(
10398 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010400 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010402 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010403
Guido van Rossumd57fd912000-03-10 22:53:23 +000010404 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 for (i = 0; i < length; i++) {
10406 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010407
Benjamin Peterson29060642009-01-31 22:14:21 +000010408 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10409 return PyBool_FromLong(0);
10410 else if (!cased && Py_UNICODE_ISUPPER(ch))
10411 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010413 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414}
10415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010416PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010417 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010419Return True if S is a titlecased string and there is at least one\n\
10420character in S, i.e. upper- and titlecase characters may only\n\
10421follow uncased characters and lowercase characters only cased ones.\n\
10422Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423
10424static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010425unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 Py_ssize_t i, length;
10428 int kind;
10429 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430 int cased, previous_is_cased;
10431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (PyUnicode_READY(self) == -1)
10433 return NULL;
10434 length = PyUnicode_GET_LENGTH(self);
10435 kind = PyUnicode_KIND(self);
10436 data = PyUnicode_DATA(self);
10437
Guido van Rossumd57fd912000-03-10 22:53:23 +000010438 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 if (length == 1) {
10440 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10441 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10442 (Py_UNICODE_ISUPPER(ch) != 0));
10443 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010445 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010447 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010448
Guido van Rossumd57fd912000-03-10 22:53:23 +000010449 cased = 0;
10450 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 for (i = 0; i < length; i++) {
10452 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010453
Benjamin Peterson29060642009-01-31 22:14:21 +000010454 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10455 if (previous_is_cased)
10456 return PyBool_FromLong(0);
10457 previous_is_cased = 1;
10458 cased = 1;
10459 }
10460 else if (Py_UNICODE_ISLOWER(ch)) {
10461 if (!previous_is_cased)
10462 return PyBool_FromLong(0);
10463 previous_is_cased = 1;
10464 cased = 1;
10465 }
10466 else
10467 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010469 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470}
10471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010472PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010473 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010475Return True if all characters in S are whitespace\n\
10476and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477
10478static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010479unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 Py_ssize_t i, length;
10482 int kind;
10483 void *data;
10484
10485 if (PyUnicode_READY(self) == -1)
10486 return NULL;
10487 length = PyUnicode_GET_LENGTH(self);
10488 kind = PyUnicode_KIND(self);
10489 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010490
Guido van Rossumd57fd912000-03-10 22:53:23 +000010491 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 if (length == 1)
10493 return PyBool_FromLong(
10494 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010495
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010496 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010498 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 for (i = 0; i < length; i++) {
10501 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010502 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010505 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506}
10507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010508PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010509 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010510\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010511Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010513
10514static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010515unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010516{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 Py_ssize_t i, length;
10518 int kind;
10519 void *data;
10520
10521 if (PyUnicode_READY(self) == -1)
10522 return NULL;
10523 length = PyUnicode_GET_LENGTH(self);
10524 kind = PyUnicode_KIND(self);
10525 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010526
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010527 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 if (length == 1)
10529 return PyBool_FromLong(
10530 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010531
10532 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010534 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 for (i = 0; i < length; i++) {
10537 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010538 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010539 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010540 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010541}
10542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010543PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010544 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010545\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010546Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010547and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010548
10549static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010550unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010551{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 int kind;
10553 void *data;
10554 Py_ssize_t len, i;
10555
10556 if (PyUnicode_READY(self) == -1)
10557 return NULL;
10558
10559 kind = PyUnicode_KIND(self);
10560 data = PyUnicode_DATA(self);
10561 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010562
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010563 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 if (len == 1) {
10565 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10566 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10567 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010568
10569 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010571 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010572
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 for (i = 0; i < len; i++) {
10574 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010575 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010576 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010577 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010578 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010579}
10580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010581PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010582 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010584Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010585False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586
10587static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010588unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 Py_ssize_t i, length;
10591 int kind;
10592 void *data;
10593
10594 if (PyUnicode_READY(self) == -1)
10595 return NULL;
10596 length = PyUnicode_GET_LENGTH(self);
10597 kind = PyUnicode_KIND(self);
10598 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010599
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (length == 1)
10602 return PyBool_FromLong(
10603 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010605 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010607 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 for (i = 0; i < length; i++) {
10610 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010611 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010613 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614}
10615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010616PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010617 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010619Return True if all characters in S are digits\n\
10620and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621
10622static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010623unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 Py_ssize_t i, length;
10626 int kind;
10627 void *data;
10628
10629 if (PyUnicode_READY(self) == -1)
10630 return NULL;
10631 length = PyUnicode_GET_LENGTH(self);
10632 kind = PyUnicode_KIND(self);
10633 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 if (length == 1) {
10637 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10638 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
10639 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010641 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 for (i = 0; i < length; i++) {
10646 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010647 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010649 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650}
10651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010652PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010653 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010655Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010656False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657
10658static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010659unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 Py_ssize_t i, length;
10662 int kind;
10663 void *data;
10664
10665 if (PyUnicode_READY(self) == -1)
10666 return NULL;
10667 length = PyUnicode_GET_LENGTH(self);
10668 kind = PyUnicode_KIND(self);
10669 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 if (length == 1)
10673 return PyBool_FromLong(
10674 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010675
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010676 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010678 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 for (i = 0; i < length; i++) {
10681 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010682 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010684 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685}
10686
Martin v. Löwis47383402007-08-15 07:32:56 +000010687int
10688PyUnicode_IsIdentifier(PyObject *self)
10689{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010690 int kind;
10691 void *data;
10692 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010693 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000010694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 if (PyUnicode_READY(self) == -1) {
10696 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000010697 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 }
10699
10700 /* Special case for empty strings */
10701 if (PyUnicode_GET_LENGTH(self) == 0)
10702 return 0;
10703 kind = PyUnicode_KIND(self);
10704 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000010705
10706 /* PEP 3131 says that the first character must be in
10707 XID_Start and subsequent characters in XID_Continue,
10708 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000010709 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000010710 letters, digits, underscore). However, given the current
10711 definition of XID_Start and XID_Continue, it is sufficient
10712 to check just for these, except that _ must be allowed
10713 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050010715 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000010716 return 0;
10717
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040010718 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010720 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000010721 return 1;
10722}
10723
10724PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000010726\n\
10727Return True if S is a valid identifier according\n\
10728to the language definition.");
10729
10730static PyObject*
10731unicode_isidentifier(PyObject *self)
10732{
10733 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
10734}
10735
Georg Brandl559e5d72008-06-11 18:37:52 +000010736PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010737 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000010738\n\
10739Return True if all characters in S are considered\n\
10740printable in repr() or S is empty, False otherwise.");
10741
10742static PyObject*
10743unicode_isprintable(PyObject *self)
10744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010745 Py_ssize_t i, length;
10746 int kind;
10747 void *data;
10748
10749 if (PyUnicode_READY(self) == -1)
10750 return NULL;
10751 length = PyUnicode_GET_LENGTH(self);
10752 kind = PyUnicode_KIND(self);
10753 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000010754
10755 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010756 if (length == 1)
10757 return PyBool_FromLong(
10758 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000010759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 for (i = 0; i < length; i++) {
10761 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000010762 Py_RETURN_FALSE;
10763 }
10764 }
10765 Py_RETURN_TRUE;
10766}
10767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010768PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000010769 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770\n\
10771Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000010772iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773
10774static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010775unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010777 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778}
10779
Martin v. Löwis18e16552006-02-15 17:27:45 +000010780static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000010781unicode_length(PyUnicodeObject *self)
10782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (PyUnicode_READY(self) == -1)
10784 return -1;
10785 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786}
10787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010788PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010789 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010790\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000010791Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010792done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793
10794static PyObject *
10795unicode_ljust(PyUnicodeObject *self, PyObject *args)
10796{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010797 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 Py_UCS4 fillchar = ' ';
10799
10800 if (PyUnicode_READY(self) == -1)
10801 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010802
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010803 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804 return NULL;
10805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807 Py_INCREF(self);
10808 return (PyObject*) self;
10809 }
10810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812}
10813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010814PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010815 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010817Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818
10819static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010820unicode_lower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 return fixup(self, fixlower);
10823}
10824
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010825#define LEFTSTRIP 0
10826#define RIGHTSTRIP 1
10827#define BOTHSTRIP 2
10828
10829/* Arrays indexed by above */
10830static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
10831
10832#define STRIPNAME(i) (stripformat[i]+3)
10833
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010834/* externally visible for str.strip(unicode) */
10835PyObject *
10836_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
10837{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 void *data;
10839 int kind;
10840 Py_ssize_t i, j, len;
10841 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
10844 return NULL;
10845
10846 kind = PyUnicode_KIND(self);
10847 data = PyUnicode_DATA(self);
10848 len = PyUnicode_GET_LENGTH(self);
10849 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
10850 PyUnicode_DATA(sepobj),
10851 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010852
Benjamin Peterson14339b62009-01-31 16:36:08 +000010853 i = 0;
10854 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010855 while (i < len &&
10856 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 i++;
10858 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010859 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010860
Benjamin Peterson14339b62009-01-31 16:36:08 +000010861 j = len;
10862 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010863 do {
10864 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010865 } while (j >= i &&
10866 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000010867 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010868 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010869
Victor Stinner12bab6d2011-10-01 01:53:49 +020010870 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010871}
10872
10873PyObject*
10874PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
10875{
10876 unsigned char *data;
10877 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020010878 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010879
Victor Stinnerde636f32011-10-01 03:55:54 +020010880 if (PyUnicode_READY(self) == -1)
10881 return NULL;
10882
10883 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
10884
Victor Stinner12bab6d2011-10-01 01:53:49 +020010885 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010886 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010887 if (PyUnicode_CheckExact(self)) {
10888 Py_INCREF(self);
10889 return self;
10890 }
10891 else
10892 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010893 }
10894
Victor Stinner12bab6d2011-10-01 01:53:49 +020010895 length = end - start;
10896 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010897 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010898
Victor Stinnerde636f32011-10-01 03:55:54 +020010899 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020010900 PyErr_SetString(PyExc_IndexError, "string index out of range");
10901 return NULL;
10902 }
10903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010904 kind = PyUnicode_KIND(self);
10905 data = PyUnicode_1BYTE_DATA(self);
Victor Stinner034f6cf2011-09-30 02:26:44 +020010906 return PyUnicode_FromKindAndData(kind,
10907 data + PyUnicode_KIND_SIZE(kind, start),
Victor Stinner12bab6d2011-10-01 01:53:49 +020010908 length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010909}
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910
10911static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010912do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010914 int kind;
10915 void *data;
10916 Py_ssize_t len, i, j;
10917
10918 if (PyUnicode_READY(self) == -1)
10919 return NULL;
10920
10921 kind = PyUnicode_KIND(self);
10922 data = PyUnicode_DATA(self);
10923 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010924
Benjamin Peterson14339b62009-01-31 16:36:08 +000010925 i = 0;
10926 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010927 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010928 i++;
10929 }
10930 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010931
Benjamin Peterson14339b62009-01-31 16:36:08 +000010932 j = len;
10933 if (striptype != LEFTSTRIP) {
10934 do {
10935 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010936 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010937 j++;
10938 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010939
Victor Stinner12bab6d2011-10-01 01:53:49 +020010940 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941}
10942
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010943
10944static PyObject *
10945do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
10946{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010947 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010948
Benjamin Peterson14339b62009-01-31 16:36:08 +000010949 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
10950 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010951
Benjamin Peterson14339b62009-01-31 16:36:08 +000010952 if (sep != NULL && sep != Py_None) {
10953 if (PyUnicode_Check(sep))
10954 return _PyUnicode_XStrip(self, striptype, sep);
10955 else {
10956 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 "%s arg must be None or str",
10958 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000010959 return NULL;
10960 }
10961 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010962
Benjamin Peterson14339b62009-01-31 16:36:08 +000010963 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010964}
10965
10966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010967PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010968 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010969\n\
10970Return a copy of the string S with leading and trailing\n\
10971whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010972If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010973
10974static PyObject *
10975unicode_strip(PyUnicodeObject *self, PyObject *args)
10976{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010977 if (PyTuple_GET_SIZE(args) == 0)
10978 return do_strip(self, BOTHSTRIP); /* Common case */
10979 else
10980 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010981}
10982
10983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010984PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010986\n\
10987Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010988If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010989
10990static PyObject *
10991unicode_lstrip(PyUnicodeObject *self, PyObject *args)
10992{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010993 if (PyTuple_GET_SIZE(args) == 0)
10994 return do_strip(self, LEFTSTRIP); /* Common case */
10995 else
10996 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000010997}
10998
10999
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011000PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011001 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011002\n\
11003Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011004If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011005
11006static PyObject *
11007unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11008{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011009 if (PyTuple_GET_SIZE(args) == 0)
11010 return do_strip(self, RIGHTSTRIP); /* Common case */
11011 else
11012 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011013}
11014
11015
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011017unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018{
11019 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011020 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021
Georg Brandl222de0f2009-04-12 12:01:50 +000011022 if (len < 1) {
11023 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011024 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026
Tim Peters7a29bd52001-09-12 03:03:31 +000011027 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028 /* no repeat, return original string */
11029 Py_INCREF(str);
11030 return (PyObject*) str;
11031 }
Tim Peters8f422462000-09-09 06:13:41 +000011032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 if (PyUnicode_READY(str) == -1)
11034 return NULL;
11035
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011036 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011037 PyErr_SetString(PyExc_OverflowError,
11038 "repeated string is too long");
11039 return NULL;
11040 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 if (!u)
11045 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011046 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 if (PyUnicode_GET_LENGTH(str) == 1) {
11049 const int kind = PyUnicode_KIND(str);
11050 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11051 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011052 if (kind == PyUnicode_1BYTE_KIND)
11053 memset(to, (unsigned char)fill_char, len);
11054 else {
11055 for (n = 0; n < len; ++n)
11056 PyUnicode_WRITE(kind, to, n, fill_char);
11057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058 }
11059 else {
11060 /* number of characters copied this far */
11061 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
11062 const Py_ssize_t char_size = PyUnicode_CHARACTER_SIZE(str);
11063 char *to = (char *) PyUnicode_DATA(u);
11064 Py_MEMCPY(to, PyUnicode_DATA(str),
11065 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011066 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011067 n = (done <= nchars-done) ? done : nchars-done;
11068 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011069 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011070 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071 }
11072
11073 return (PyObject*) u;
11074}
11075
Alexander Belopolsky40018472011-02-26 01:02:56 +000011076PyObject *
11077PyUnicode_Replace(PyObject *obj,
11078 PyObject *subobj,
11079 PyObject *replobj,
11080 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081{
11082 PyObject *self;
11083 PyObject *str1;
11084 PyObject *str2;
11085 PyObject *result;
11086
11087 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011088 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011091 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011092 Py_DECREF(self);
11093 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094 }
11095 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011096 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011097 Py_DECREF(self);
11098 Py_DECREF(str1);
11099 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011101 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 Py_DECREF(self);
11103 Py_DECREF(str1);
11104 Py_DECREF(str2);
11105 return result;
11106}
11107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011108PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011109 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011110\n\
11111Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011112old replaced by new. If the optional argument count is\n\
11113given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114
11115static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011116unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011118 PyObject *str1;
11119 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011120 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 PyObject *result;
11122
Martin v. Löwis18e16552006-02-15 17:27:45 +000011123 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011126 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 str1 = PyUnicode_FromObject(str1);
11128 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11129 return NULL;
11130 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011131 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011132 Py_DECREF(str1);
11133 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011134 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135
11136 result = replace(self, str1, str2, maxcount);
11137
11138 Py_DECREF(str1);
11139 Py_DECREF(str2);
11140 return result;
11141}
11142
Alexander Belopolsky40018472011-02-26 01:02:56 +000011143static PyObject *
11144unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011146 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 Py_ssize_t isize;
11148 Py_ssize_t osize, squote, dquote, i, o;
11149 Py_UCS4 max, quote;
11150 int ikind, okind;
11151 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011152
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011154 return NULL;
11155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 isize = PyUnicode_GET_LENGTH(unicode);
11157 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 /* Compute length of output, quote characters, and
11160 maximum character */
11161 osize = 2; /* quotes */
11162 max = 127;
11163 squote = dquote = 0;
11164 ikind = PyUnicode_KIND(unicode);
11165 for (i = 0; i < isize; i++) {
11166 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11167 switch (ch) {
11168 case '\'': squote++; osize++; break;
11169 case '"': dquote++; osize++; break;
11170 case '\\': case '\t': case '\r': case '\n':
11171 osize += 2; break;
11172 default:
11173 /* Fast-path ASCII */
11174 if (ch < ' ' || ch == 0x7f)
11175 osize += 4; /* \xHH */
11176 else if (ch < 0x7f)
11177 osize++;
11178 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11179 osize++;
11180 max = ch > max ? ch : max;
11181 }
11182 else if (ch < 0x100)
11183 osize += 4; /* \xHH */
11184 else if (ch < 0x10000)
11185 osize += 6; /* \uHHHH */
11186 else
11187 osize += 10; /* \uHHHHHHHH */
11188 }
11189 }
11190
11191 quote = '\'';
11192 if (squote) {
11193 if (dquote)
11194 /* Both squote and dquote present. Use squote,
11195 and escape them */
11196 osize += squote;
11197 else
11198 quote = '"';
11199 }
11200
11201 repr = PyUnicode_New(osize, max);
11202 if (repr == NULL)
11203 return NULL;
11204 okind = PyUnicode_KIND(repr);
11205 odata = PyUnicode_DATA(repr);
11206
11207 PyUnicode_WRITE(okind, odata, 0, quote);
11208 PyUnicode_WRITE(okind, odata, osize-1, quote);
11209
11210 for (i = 0, o = 1; i < isize; i++) {
11211 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011212
11213 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 if ((ch == quote) || (ch == '\\')) {
11215 PyUnicode_WRITE(okind, odata, o++, '\\');
11216 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011217 continue;
11218 }
11219
Benjamin Peterson29060642009-01-31 22:14:21 +000011220 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011221 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 PyUnicode_WRITE(okind, odata, o++, '\\');
11223 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011224 }
11225 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 PyUnicode_WRITE(okind, odata, o++, '\\');
11227 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011228 }
11229 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011230 PyUnicode_WRITE(okind, odata, o++, '\\');
11231 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011232 }
11233
11234 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011235 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 PyUnicode_WRITE(okind, odata, o++, '\\');
11237 PyUnicode_WRITE(okind, odata, o++, 'x');
11238 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11239 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011240 }
11241
Georg Brandl559e5d72008-06-11 18:37:52 +000011242 /* Copy ASCII characters as-is */
11243 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011244 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011245 }
11246
Benjamin Peterson29060642009-01-31 22:14:21 +000011247 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011248 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011249 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011250 (categories Z* and C* except ASCII space)
11251 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011252 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011253 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 if (ch <= 0xff) {
11255 PyUnicode_WRITE(okind, odata, o++, '\\');
11256 PyUnicode_WRITE(okind, odata, o++, 'x');
11257 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11258 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011259 }
11260 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 else if (ch >= 0x10000) {
11262 PyUnicode_WRITE(okind, odata, o++, '\\');
11263 PyUnicode_WRITE(okind, odata, o++, 'U');
11264 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11265 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11266 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11267 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11268 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11269 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11270 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11271 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011272 }
11273 /* Map 16-bit characters to '\uxxxx' */
11274 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011275 PyUnicode_WRITE(okind, odata, o++, '\\');
11276 PyUnicode_WRITE(okind, odata, o++, 'u');
11277 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11278 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11279 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11280 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011281 }
11282 }
11283 /* Copy characters as-is */
11284 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011286 }
11287 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011288 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 /* Closing quote already added at the beginning */
Walter Dörwald79e913e2007-05-12 11:08:06 +000011290 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291}
11292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295\n\
11296Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011297such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298arguments start and end are interpreted as in slice notation.\n\
11299\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011300Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301
11302static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304{
Jesus Ceaac451502011-04-20 17:09:23 +020011305 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011306 Py_ssize_t start;
11307 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011308 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
Jesus Ceaac451502011-04-20 17:09:23 +020011310 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11311 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011312 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (PyUnicode_READY(self) == -1)
11315 return NULL;
11316 if (PyUnicode_READY(substring) == -1)
11317 return NULL;
11318
11319 result = any_find_slice(
11320 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11321 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011322 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323
11324 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 if (result == -2)
11327 return NULL;
11328
Christian Heimes217cfd12007-12-02 14:31:20 +000011329 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330}
11331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011335Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
11337static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339{
Jesus Ceaac451502011-04-20 17:09:23 +020011340 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011341 Py_ssize_t start;
11342 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011343 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
Jesus Ceaac451502011-04-20 17:09:23 +020011345 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11346 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011347 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 if (PyUnicode_READY(self) == -1)
11350 return NULL;
11351 if (PyUnicode_READY(substring) == -1)
11352 return NULL;
11353
11354 result = any_find_slice(
11355 ucs1lib_rfind_slice, ucs2lib_rfind_slice, ucs4lib_rfind_slice,
11356 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011357 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
11359 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011361 if (result == -2)
11362 return NULL;
11363
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364 if (result < 0) {
11365 PyErr_SetString(PyExc_ValueError, "substring not found");
11366 return NULL;
11367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368
Christian Heimes217cfd12007-12-02 14:31:20 +000011369 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370}
11371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011372PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011375Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011376done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377
11378static PyObject *
11379unicode_rjust(PyUnicodeObject *self, PyObject *args)
11380{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011381 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 Py_UCS4 fillchar = ' ';
11383
Victor Stinnere9a29352011-10-01 02:14:59 +020011384 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011385 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011386
Victor Stinnere9a29352011-10-01 02:14:59 +020011387 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388 return NULL;
11389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 Py_INCREF(self);
11392 return (PyObject*) self;
11393 }
11394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396}
11397
Alexander Belopolsky40018472011-02-26 01:02:56 +000011398PyObject *
11399PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400{
11401 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011402
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 s = PyUnicode_FromObject(s);
11404 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011405 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 if (sep != NULL) {
11407 sep = PyUnicode_FromObject(sep);
11408 if (sep == NULL) {
11409 Py_DECREF(s);
11410 return NULL;
11411 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412 }
11413
11414 result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11415
11416 Py_DECREF(s);
11417 Py_XDECREF(sep);
11418 return result;
11419}
11420
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011421PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423\n\
11424Return a list of the words in S, using sep as the\n\
11425delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011426splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011427whitespace string is a separator and empty strings are\n\
11428removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
11430static PyObject*
11431unicode_split(PyUnicodeObject *self, PyObject *args)
11432{
11433 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011434 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435
Martin v. Löwis18e16552006-02-15 17:27:45 +000011436 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 return NULL;
11438
11439 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 return split(self, (PyUnicodeObject *)substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445}
11446
Thomas Wouters477c8d52006-05-27 19:21:47 +000011447PyObject *
11448PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11449{
11450 PyObject* str_obj;
11451 PyObject* sep_obj;
11452 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 int kind1, kind2, kind;
11454 void *buf1 = NULL, *buf2 = NULL;
11455 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011456
11457 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011458 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011460 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011462 Py_DECREF(str_obj);
11463 return NULL;
11464 }
11465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 kind1 = PyUnicode_KIND(str_in);
11467 kind2 = PyUnicode_KIND(sep_obj);
11468 kind = kind1 > kind2 ? kind1 : kind2;
11469 buf1 = PyUnicode_DATA(str_in);
11470 if (kind1 != kind)
11471 buf1 = _PyUnicode_AsKind(str_in, kind);
11472 if (!buf1)
11473 goto onError;
11474 buf2 = PyUnicode_DATA(sep_obj);
11475 if (kind2 != kind)
11476 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11477 if (!buf2)
11478 goto onError;
11479 len1 = PyUnicode_GET_LENGTH(str_obj);
11480 len2 = PyUnicode_GET_LENGTH(sep_obj);
11481
11482 switch(PyUnicode_KIND(str_in)) {
11483 case PyUnicode_1BYTE_KIND:
11484 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11485 break;
11486 case PyUnicode_2BYTE_KIND:
11487 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11488 break;
11489 case PyUnicode_4BYTE_KIND:
11490 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11491 break;
11492 default:
11493 assert(0);
11494 out = 0;
11495 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011496
11497 Py_DECREF(sep_obj);
11498 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 if (kind1 != kind)
11500 PyMem_Free(buf1);
11501 if (kind2 != kind)
11502 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011503
11504 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 onError:
11506 Py_DECREF(sep_obj);
11507 Py_DECREF(str_obj);
11508 if (kind1 != kind && buf1)
11509 PyMem_Free(buf1);
11510 if (kind2 != kind && buf2)
11511 PyMem_Free(buf2);
11512 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011513}
11514
11515
11516PyObject *
11517PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11518{
11519 PyObject* str_obj;
11520 PyObject* sep_obj;
11521 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 int kind1, kind2, kind;
11523 void *buf1 = NULL, *buf2 = NULL;
11524 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011525
11526 str_obj = PyUnicode_FromObject(str_in);
11527 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011529 sep_obj = PyUnicode_FromObject(sep_in);
11530 if (!sep_obj) {
11531 Py_DECREF(str_obj);
11532 return NULL;
11533 }
11534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 kind1 = PyUnicode_KIND(str_in);
11536 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011537 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 buf1 = PyUnicode_DATA(str_in);
11539 if (kind1 != kind)
11540 buf1 = _PyUnicode_AsKind(str_in, kind);
11541 if (!buf1)
11542 goto onError;
11543 buf2 = PyUnicode_DATA(sep_obj);
11544 if (kind2 != kind)
11545 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11546 if (!buf2)
11547 goto onError;
11548 len1 = PyUnicode_GET_LENGTH(str_obj);
11549 len2 = PyUnicode_GET_LENGTH(sep_obj);
11550
11551 switch(PyUnicode_KIND(str_in)) {
11552 case PyUnicode_1BYTE_KIND:
11553 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11554 break;
11555 case PyUnicode_2BYTE_KIND:
11556 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11557 break;
11558 case PyUnicode_4BYTE_KIND:
11559 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11560 break;
11561 default:
11562 assert(0);
11563 out = 0;
11564 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011565
11566 Py_DECREF(sep_obj);
11567 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 if (kind1 != kind)
11569 PyMem_Free(buf1);
11570 if (kind2 != kind)
11571 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011572
11573 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 onError:
11575 Py_DECREF(sep_obj);
11576 Py_DECREF(str_obj);
11577 if (kind1 != kind && buf1)
11578 PyMem_Free(buf1);
11579 if (kind2 != kind && buf2)
11580 PyMem_Free(buf2);
11581 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011582}
11583
11584PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011585 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011586\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011587Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011588the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011589found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011590
11591static PyObject*
11592unicode_partition(PyUnicodeObject *self, PyObject *separator)
11593{
11594 return PyUnicode_Partition((PyObject *)self, separator);
11595}
11596
11597PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000011598 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011599\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000011600Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011601the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011602separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000011603
11604static PyObject*
11605unicode_rpartition(PyUnicodeObject *self, PyObject *separator)
11606{
11607 return PyUnicode_RPartition((PyObject *)self, separator);
11608}
11609
Alexander Belopolsky40018472011-02-26 01:02:56 +000011610PyObject *
11611PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011612{
11613 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011614
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011615 s = PyUnicode_FromObject(s);
11616 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011617 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 if (sep != NULL) {
11619 sep = PyUnicode_FromObject(sep);
11620 if (sep == NULL) {
11621 Py_DECREF(s);
11622 return NULL;
11623 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011624 }
11625
11626 result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
11627
11628 Py_DECREF(s);
11629 Py_XDECREF(sep);
11630 return result;
11631}
11632
11633PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011635\n\
11636Return a list of the words in S, using sep as the\n\
11637delimiter string, starting at the end of the string and\n\
11638working to the front. If maxsplit is given, at most maxsplit\n\
11639splits are done. If sep is not specified, any whitespace string\n\
11640is a separator.");
11641
11642static PyObject*
11643unicode_rsplit(PyUnicodeObject *self, PyObject *args)
11644{
11645 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011646 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011647
Martin v. Löwis18e16552006-02-15 17:27:45 +000011648 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011649 return NULL;
11650
11651 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011652 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011653 else if (PyUnicode_Check(substring))
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 return rsplit(self, (PyUnicodeObject *)substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011655 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011656 return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000011657}
11658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011659PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011660 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661\n\
11662Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000011663Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
11666static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011667unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011669 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000011670 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010011672 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
11673 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674 return NULL;
11675
Guido van Rossum86662912000-04-11 15:38:46 +000011676 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677}
11678
11679static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000011680PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681{
Walter Dörwald346737f2007-05-31 10:44:43 +000011682 if (PyUnicode_CheckExact(self)) {
11683 Py_INCREF(self);
11684 return self;
11685 } else
11686 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020011687 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688}
11689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011690PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692\n\
11693Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011694and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695
11696static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011697unicode_swapcase(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699 return fixup(self, fixswapcase);
11700}
11701
Georg Brandlceee0772007-11-27 23:48:05 +000011702PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011703 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011704\n\
11705Return a translation table usable for str.translate().\n\
11706If there is only one argument, it must be a dictionary mapping Unicode\n\
11707ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011708Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000011709If there are two arguments, they must be strings of equal length, and\n\
11710in the resulting dictionary, each character in x will be mapped to the\n\
11711character at the same position in y. If there is a third argument, it\n\
11712must be a string, whose characters will be mapped to None in the result.");
11713
11714static PyObject*
11715unicode_maketrans(PyUnicodeObject *null, PyObject *args)
11716{
11717 PyObject *x, *y = NULL, *z = NULL;
11718 PyObject *new = NULL, *key, *value;
11719 Py_ssize_t i = 0;
11720 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011721
Georg Brandlceee0772007-11-27 23:48:05 +000011722 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
11723 return NULL;
11724 new = PyDict_New();
11725 if (!new)
11726 return NULL;
11727 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 int x_kind, y_kind, z_kind;
11729 void *x_data, *y_data, *z_data;
11730
Georg Brandlceee0772007-11-27 23:48:05 +000011731 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000011732 if (!PyUnicode_Check(x)) {
11733 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
11734 "be a string if there is a second argument");
11735 goto err;
11736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011738 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
11739 "arguments must have equal length");
11740 goto err;
11741 }
11742 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 x_kind = PyUnicode_KIND(x);
11744 y_kind = PyUnicode_KIND(y);
11745 x_data = PyUnicode_DATA(x);
11746 y_data = PyUnicode_DATA(y);
11747 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
11748 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
11749 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011750 if (!key || !value)
11751 goto err;
11752 res = PyDict_SetItem(new, key, value);
11753 Py_DECREF(key);
11754 Py_DECREF(value);
11755 if (res < 0)
11756 goto err;
11757 }
11758 /* create entries for deleting chars in z */
11759 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 z_kind = PyUnicode_KIND(z);
11761 z_data = PyUnicode_DATA(z);
Georg Brandlceee0772007-11-27 23:48:05 +000011762 for (i = 0; i < PyUnicode_GET_SIZE(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000011764 if (!key)
11765 goto err;
11766 res = PyDict_SetItem(new, key, Py_None);
11767 Py_DECREF(key);
11768 if (res < 0)
11769 goto err;
11770 }
11771 }
11772 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 int kind;
11774 void *data;
11775
Georg Brandlceee0772007-11-27 23:48:05 +000011776 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000011777 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011778 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
11779 "to maketrans it must be a dict");
11780 goto err;
11781 }
11782 /* copy entries into the new dict, converting string keys to int keys */
11783 while (PyDict_Next(x, &i, &key, &value)) {
11784 if (PyUnicode_Check(key)) {
11785 /* convert string keys to integer keys */
11786 PyObject *newkey;
11787 if (PyUnicode_GET_SIZE(key) != 1) {
11788 PyErr_SetString(PyExc_ValueError, "string keys in translate "
11789 "table must be of length 1");
11790 goto err;
11791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 kind = PyUnicode_KIND(key);
11793 data = PyUnicode_DATA(key);
11794 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000011795 if (!newkey)
11796 goto err;
11797 res = PyDict_SetItem(new, newkey, value);
11798 Py_DECREF(newkey);
11799 if (res < 0)
11800 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000011801 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000011802 /* just keep integer keys */
11803 if (PyDict_SetItem(new, key, value) < 0)
11804 goto err;
11805 } else {
11806 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
11807 "be strings or integers");
11808 goto err;
11809 }
11810 }
11811 }
11812 return new;
11813 err:
11814 Py_DECREF(new);
11815 return NULL;
11816}
11817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011818PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820\n\
11821Return a copy of the string S, where all characters have been mapped\n\
11822through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011823Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000011824Unmapped characters are left untouched. Characters mapped to None\n\
11825are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826
11827static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831}
11832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011833PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011834 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011836Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837
11838static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011839unicode_upper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841 return fixup(self, fixupper);
11842}
11843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011844PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000011847Pad a numeric string S with zeros on the left, to fill a field\n\
11848of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849
11850static PyObject *
11851unicode_zfill(PyUnicodeObject *self, PyObject *args)
11852{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011853 Py_ssize_t fill;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 PyUnicodeObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011855 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 int kind;
11857 void *data;
11858 Py_UCS4 chr;
11859
11860 if (PyUnicode_READY(self) == -1)
11861 return NULL;
11862
Martin v. Löwis18e16552006-02-15 17:27:45 +000011863 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864 return NULL;
11865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000011867 if (PyUnicode_CheckExact(self)) {
11868 Py_INCREF(self);
11869 return (PyObject*) self;
11870 }
11871 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020011872 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 }
11874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876
11877 u = pad(self, fill, 0, '0');
11878
Walter Dörwald068325e2002-04-15 13:36:47 +000011879 if (u == NULL)
11880 return NULL;
11881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 kind = PyUnicode_KIND(u);
11883 data = PyUnicode_DATA(u);
11884 chr = PyUnicode_READ(kind, data, fill);
11885
11886 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 PyUnicode_WRITE(kind, data, 0, chr);
11889 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890 }
11891
11892 return (PyObject*) u;
11893}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
11895#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011896static PyObject *
11897unicode__decimal2ascii(PyObject *self)
11898{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011899 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000011900}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901#endif
11902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011903PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011904 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011906Return True if S starts with the specified prefix, False otherwise.\n\
11907With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011908With optional end, stop comparing S at that position.\n\
11909prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910
11911static PyObject *
11912unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011913 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011915 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011917 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011918 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011919 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
Jesus Ceaac451502011-04-20 17:09:23 +020011921 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011923 if (PyTuple_Check(subobj)) {
11924 Py_ssize_t i;
11925 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11926 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011927 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011928 if (substring == NULL)
11929 return NULL;
11930 result = tailmatch(self, substring, start, end, -1);
11931 Py_DECREF(substring);
11932 if (result) {
11933 Py_RETURN_TRUE;
11934 }
11935 }
11936 /* nothing matched */
11937 Py_RETURN_FALSE;
11938 }
11939 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011940 if (substring == NULL) {
11941 if (PyErr_ExceptionMatches(PyExc_TypeError))
11942 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
11943 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011944 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011945 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011946 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011948 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949}
11950
11951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011952PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000011955Return True if S ends with the specified suffix, False otherwise.\n\
11956With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011957With optional end, stop comparing S at that position.\n\
11958suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
11960static PyObject *
11961unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000011962 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011963{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011964 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011966 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011967 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011968 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969
Jesus Ceaac451502011-04-20 17:09:23 +020011970 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011972 if (PyTuple_Check(subobj)) {
11973 Py_ssize_t i;
11974 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
11975 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000011976 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011977 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011979 result = tailmatch(self, substring, start, end, +1);
11980 Py_DECREF(substring);
11981 if (result) {
11982 Py_RETURN_TRUE;
11983 }
11984 }
11985 Py_RETURN_FALSE;
11986 }
11987 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030011988 if (substring == NULL) {
11989 if (PyErr_ExceptionMatches(PyExc_TypeError))
11990 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
11991 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000011992 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030011993 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011994 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011996 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997}
11998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012000
12001PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012003\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012004Return a formatted version of S, using substitutions from args and kwargs.\n\
12005The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012006
Eric Smith27bbca62010-11-04 17:06:58 +000012007PyDoc_STRVAR(format_map__doc__,
12008 "S.format_map(mapping) -> str\n\
12009\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012010Return a formatted version of S, using substitutions from mapping.\n\
12011The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012012
Eric Smith4a7d76d2008-05-30 18:10:19 +000012013static PyObject *
12014unicode__format__(PyObject* self, PyObject* args)
12015{
12016 PyObject *format_spec;
12017
12018 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12019 return NULL;
12020
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 return _PyUnicode_FormatAdvanced(self, format_spec, 0,
12022 PyUnicode_GET_LENGTH(format_spec));
Eric Smith4a7d76d2008-05-30 18:10:19 +000012023}
12024
Eric Smith8c663262007-08-25 02:26:07 +000012025PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012026 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012027\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012028Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012029
12030static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012031unicode__sizeof__(PyUnicodeObject *v)
12032{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 Py_ssize_t size;
12034
12035 /* If it's a compact object, account for base structure +
12036 character data. */
12037 if (PyUnicode_IS_COMPACT_ASCII(v))
12038 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12039 else if (PyUnicode_IS_COMPACT(v))
12040 size = sizeof(PyCompactUnicodeObject) +
12041 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_CHARACTER_SIZE(v);
12042 else {
12043 /* If it is a two-block object, account for base object, and
12044 for character block if present. */
12045 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012046 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 size += (PyUnicode_GET_LENGTH(v) + 1) *
12048 PyUnicode_CHARACTER_SIZE(v);
12049 }
12050 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012051 with the data pointer. Check if the data is not shared. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 if (_PyUnicode_WSTR(v) &&
Victor Stinnera3be6132011-10-03 02:16:37 +020012053 (PyUnicode_DATA(v) != _PyUnicode_WSTR(v)))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012055 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012056 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057
12058 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012059}
12060
12061PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012062 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012063
12064static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012065unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012066{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012067 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (!copy)
12069 return NULL;
12070 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012071}
12072
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073static PyMethodDef unicode_methods[] = {
12074
12075 /* Order is according to common usage: often used methods should
12076 appear first, since lookup is done sequentially. */
12077
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012078 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012079 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12080 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012081 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012082 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12083 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12084 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12085 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12086 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12087 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12088 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012089 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012090 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12091 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12092 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012093 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012094 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12095 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12096 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012097 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012098 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012099 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012100 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012101 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12102 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12103 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12104 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12105 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12106 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12107 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12108 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12109 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12110 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12111 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12112 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12113 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12114 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012115 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012116 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012117 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012118 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012119 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012120 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012121 {"maketrans", (PyCFunction) unicode_maketrans,
12122 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012123 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012124#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012125 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126#endif
12127
12128#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012129 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012130 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131#endif
12132
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134 {NULL, NULL}
12135};
12136
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012137static PyObject *
12138unicode_mod(PyObject *v, PyObject *w)
12139{
Brian Curtindfc80e32011-08-10 20:28:54 -050012140 if (!PyUnicode_Check(v))
12141 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012142 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012143}
12144
12145static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 0, /*nb_add*/
12147 0, /*nb_subtract*/
12148 0, /*nb_multiply*/
12149 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012150};
12151
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012153 (lenfunc) unicode_length, /* sq_length */
12154 PyUnicode_Concat, /* sq_concat */
12155 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12156 (ssizeargfunc) unicode_getitem, /* sq_item */
12157 0, /* sq_slice */
12158 0, /* sq_ass_item */
12159 0, /* sq_ass_slice */
12160 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161};
12162
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012163static PyObject*
12164unicode_subscript(PyUnicodeObject* self, PyObject* item)
12165{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 if (PyUnicode_READY(self) == -1)
12167 return NULL;
12168
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012169 if (PyIndex_Check(item)) {
12170 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012171 if (i == -1 && PyErr_Occurred())
12172 return NULL;
12173 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012175 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012176 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012177 Py_ssize_t start, stop, step, slicelength, cur, i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012178 const Py_UNICODE* source_buf;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012179 Py_UNICODE* result_buf;
12180 PyObject* result;
12181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012183 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012184 return NULL;
12185 }
12186
12187 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 return PyUnicode_New(0, 0);
12189 } else if (start == 0 && step == 1 &&
12190 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012191 PyUnicode_CheckExact(self)) {
12192 Py_INCREF(self);
12193 return (PyObject *)self;
12194 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012195 return PyUnicode_Substring((PyObject*)self,
12196 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012197 } else {
12198 source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
Christian Heimesb186d002008-03-18 15:15:01 +000012199 result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
12200 sizeof(Py_UNICODE));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012201
Benjamin Peterson29060642009-01-31 22:14:21 +000012202 if (result_buf == NULL)
12203 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012204
12205 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12206 result_buf[i] = source_buf[cur];
12207 }
Tim Petersced69f82003-09-16 20:30:58 +000012208
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012209 result = PyUnicode_FromUnicode(result_buf, slicelength);
Christian Heimesb186d002008-03-18 15:15:01 +000012210 PyObject_FREE(result_buf);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012211 return result;
12212 }
12213 } else {
12214 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12215 return NULL;
12216 }
12217}
12218
12219static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012220 (lenfunc)unicode_length, /* mp_length */
12221 (binaryfunc)unicode_subscript, /* mp_subscript */
12222 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012223};
12224
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226/* Helpers for PyUnicode_Format() */
12227
12228static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012229getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012231 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012233 (*p_argidx)++;
12234 if (arglen < 0)
12235 return args;
12236 else
12237 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238 }
12239 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012240 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241 return NULL;
12242}
12243
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012244/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012246static PyObject *
12247formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012249 char *p;
12250 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012252
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253 x = PyFloat_AsDouble(v);
12254 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012255 return NULL;
12256
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012259
Eric Smith0923d1d2009-04-16 20:16:10 +000012260 p = PyOS_double_to_string(x, type, prec,
12261 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012262 if (p == NULL)
12263 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012265 PyMem_Free(p);
12266 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267}
12268
Tim Peters38fd5b62000-09-21 05:43:11 +000012269static PyObject*
12270formatlong(PyObject *val, int flags, int prec, int type)
12271{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012272 char *buf;
12273 int len;
12274 PyObject *str; /* temporary string object. */
12275 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012276
Benjamin Peterson14339b62009-01-31 16:36:08 +000012277 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12278 if (!str)
12279 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012280 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012281 Py_DECREF(str);
12282 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012283}
12284
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286formatchar(Py_UCS4 *buf,
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012287 size_t buflen,
12288 PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012290 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012291 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (PyUnicode_GET_LENGTH(v) == 1) {
12293 buf[0] = PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012294 buf[1] = '\0';
12295 return 1;
12296 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012297 goto onError;
12298 }
12299 else {
12300 /* Integer input truncated to a character */
12301 long x;
12302 x = PyLong_AsLong(v);
12303 if (x == -1 && PyErr_Occurred())
12304 goto onError;
12305
12306 if (x < 0 || x > 0x10ffff) {
12307 PyErr_SetString(PyExc_OverflowError,
12308 "%c arg not in range(0x110000)");
12309 return -1;
12310 }
12311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 buf[0] = (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012313 buf[1] = '\0';
12314 return 1;
12315 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012316
Benjamin Peterson29060642009-01-31 22:14:21 +000012317 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012318 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012319 "%c requires int or char");
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012320 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012321}
12322
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012323/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012324 FORMATBUFLEN is the length of the buffer in which chars are formatted.
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012325*/
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012326#define FORMATBUFLEN (size_t)10
Marc-André Lemburgf28dd832000-06-30 10:29:57 +000012327
Alexander Belopolsky40018472011-02-26 01:02:56 +000012328PyObject *
12329PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 void *fmt;
12332 int fmtkind;
12333 PyObject *result;
12334 Py_UCS4 *res, *res0;
12335 Py_UCS4 max;
12336 int kind;
12337 Py_ssize_t fmtcnt, fmtpos, rescnt, reslen, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 PyObject *dict = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 PyUnicodeObject *uformat;
Tim Petersced69f82003-09-16 20:30:58 +000012341
Guido van Rossumd57fd912000-03-10 22:53:23 +000012342 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 PyErr_BadInternalCall();
12344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12347 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012348 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 fmt = PyUnicode_DATA(uformat);
12350 fmtkind = PyUnicode_KIND(uformat);
12351 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12352 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353
12354 reslen = rescnt = fmtcnt + 100;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 res = res0 = PyMem_Malloc(reslen * sizeof(Py_UCS4));
12356 if (res0 == NULL) {
12357 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012358 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360
12361 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012362 arglen = PyTuple_Size(args);
12363 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012364 }
12365 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012366 arglen = -1;
12367 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012368 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012369 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012370 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372
12373 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012375 if (--rescnt < 0) {
12376 rescnt = fmtcnt + 100;
12377 reslen += rescnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12379 if (res0 == NULL){
12380 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 }
12383 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012384 --rescnt;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386 *res++ = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012387 }
12388 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012389 /* Got a format specifier */
12390 int flags = 0;
12391 Py_ssize_t width = -1;
12392 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 Py_UCS4 c = '\0';
12394 Py_UCS4 fill;
Benjamin Peterson29060642009-01-31 22:14:21 +000012395 int isnumok;
12396 PyObject *v = NULL;
12397 PyObject *temp = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 void *pbuf;
12399 Py_ssize_t pindex;
Benjamin Peterson29060642009-01-31 22:14:21 +000012400 Py_UNICODE sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 Py_ssize_t len, len1;
12402 Py_UCS4 formatbuf[FORMATBUFLEN]; /* For formatchar() */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 fmtpos++;
12405 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12406 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012407 Py_ssize_t keylen;
12408 PyObject *key;
12409 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012410
Benjamin Peterson29060642009-01-31 22:14:21 +000012411 if (dict == NULL) {
12412 PyErr_SetString(PyExc_TypeError,
12413 "format requires a mapping");
12414 goto onError;
12415 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012417 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 /* Skip over balanced parentheses */
12420 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012421 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012422 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012424 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012428 if (fmtcnt < 0 || pcount > 0) {
12429 PyErr_SetString(PyExc_ValueError,
12430 "incomplete format key");
12431 goto onError;
12432 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012433 key = PyUnicode_Substring((PyObject*)uformat,
12434 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012435 if (key == NULL)
12436 goto onError;
12437 if (args_owned) {
12438 Py_DECREF(args);
12439 args_owned = 0;
12440 }
12441 args = PyObject_GetItem(dict, key);
12442 Py_DECREF(key);
12443 if (args == NULL) {
12444 goto onError;
12445 }
12446 args_owned = 1;
12447 arglen = -1;
12448 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012449 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012450 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012452 case '-': flags |= F_LJUST; continue;
12453 case '+': flags |= F_SIGN; continue;
12454 case ' ': flags |= F_BLANK; continue;
12455 case '#': flags |= F_ALT; continue;
12456 case '0': flags |= F_ZERO; continue;
12457 }
12458 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012459 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012460 if (c == '*') {
12461 v = getnextarg(args, arglen, &argidx);
12462 if (v == NULL)
12463 goto onError;
12464 if (!PyLong_Check(v)) {
12465 PyErr_SetString(PyExc_TypeError,
12466 "* wants int");
12467 goto onError;
12468 }
12469 width = PyLong_AsLong(v);
12470 if (width == -1 && PyErr_Occurred())
12471 goto onError;
12472 if (width < 0) {
12473 flags |= F_LJUST;
12474 width = -width;
12475 }
12476 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012478 }
12479 else if (c >= '0' && c <= '9') {
12480 width = c - '0';
12481 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012483 if (c < '0' || c > '9')
12484 break;
12485 if ((width*10) / 10 != width) {
12486 PyErr_SetString(PyExc_ValueError,
12487 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012488 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 }
12490 width = width*10 + (c - '0');
12491 }
12492 }
12493 if (c == '.') {
12494 prec = 0;
12495 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012497 if (c == '*') {
12498 v = getnextarg(args, arglen, &argidx);
12499 if (v == NULL)
12500 goto onError;
12501 if (!PyLong_Check(v)) {
12502 PyErr_SetString(PyExc_TypeError,
12503 "* wants int");
12504 goto onError;
12505 }
12506 prec = PyLong_AsLong(v);
12507 if (prec == -1 && PyErr_Occurred())
12508 goto onError;
12509 if (prec < 0)
12510 prec = 0;
12511 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 }
12514 else if (c >= '0' && c <= '9') {
12515 prec = c - '0';
12516 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012518 if (c < '0' || c > '9')
12519 break;
12520 if ((prec*10) / 10 != prec) {
12521 PyErr_SetString(PyExc_ValueError,
12522 "prec too big");
12523 goto onError;
12524 }
12525 prec = prec*10 + (c - '0');
12526 }
12527 }
12528 } /* prec */
12529 if (fmtcnt >= 0) {
12530 if (c == 'h' || c == 'l' || c == 'L') {
12531 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012533 }
12534 }
12535 if (fmtcnt < 0) {
12536 PyErr_SetString(PyExc_ValueError,
12537 "incomplete format");
12538 goto onError;
12539 }
12540 if (c != '%') {
12541 v = getnextarg(args, arglen, &argidx);
12542 if (v == NULL)
12543 goto onError;
12544 }
12545 sign = 0;
12546 fill = ' ';
12547 switch (c) {
12548
12549 case '%':
12550 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012551 kind = PyUnicode_4BYTE_KIND;
Benjamin Peterson29060642009-01-31 22:14:21 +000012552 /* presume that buffer length is at least 1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 PyUnicode_WRITE(kind, pbuf, 0, '%');
Benjamin Peterson29060642009-01-31 22:14:21 +000012554 len = 1;
12555 break;
12556
12557 case 's':
12558 case 'r':
12559 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000012560 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000012561 temp = v;
12562 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012563 }
12564 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012565 if (c == 's')
12566 temp = PyObject_Str(v);
12567 else if (c == 'r')
12568 temp = PyObject_Repr(v);
12569 else
12570 temp = PyObject_ASCII(v);
12571 if (temp == NULL)
12572 goto onError;
12573 if (PyUnicode_Check(temp))
12574 /* nothing to do */;
12575 else {
12576 Py_DECREF(temp);
12577 PyErr_SetString(PyExc_TypeError,
12578 "%s argument has non-string str()");
12579 goto onError;
12580 }
12581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 if (PyUnicode_READY(temp) == -1) {
12583 Py_CLEAR(temp);
12584 goto onError;
12585 }
12586 pbuf = PyUnicode_DATA(temp);
12587 kind = PyUnicode_KIND(temp);
12588 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012589 if (prec >= 0 && len > prec)
12590 len = prec;
12591 break;
12592
12593 case 'i':
12594 case 'd':
12595 case 'u':
12596 case 'o':
12597 case 'x':
12598 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 isnumok = 0;
12600 if (PyNumber_Check(v)) {
12601 PyObject *iobj=NULL;
12602
12603 if (PyLong_Check(v)) {
12604 iobj = v;
12605 Py_INCREF(iobj);
12606 }
12607 else {
12608 iobj = PyNumber_Long(v);
12609 }
12610 if (iobj!=NULL) {
12611 if (PyLong_Check(iobj)) {
12612 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070012613 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 Py_DECREF(iobj);
12615 if (!temp)
12616 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 if (PyUnicode_READY(temp) == -1) {
12618 Py_CLEAR(temp);
12619 goto onError;
12620 }
12621 pbuf = PyUnicode_DATA(temp);
12622 kind = PyUnicode_KIND(temp);
12623 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012624 sign = 1;
12625 }
12626 else {
12627 Py_DECREF(iobj);
12628 }
12629 }
12630 }
12631 if (!isnumok) {
12632 PyErr_Format(PyExc_TypeError,
12633 "%%%c format: a number is required, "
12634 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
12635 goto onError;
12636 }
12637 if (flags & F_ZERO)
12638 fill = '0';
12639 break;
12640
12641 case 'e':
12642 case 'E':
12643 case 'f':
12644 case 'F':
12645 case 'g':
12646 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012647 temp = formatfloat(v, flags, prec, c);
12648 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000012649 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 if (PyUnicode_READY(temp) == -1) {
12651 Py_CLEAR(temp);
12652 goto onError;
12653 }
12654 pbuf = PyUnicode_DATA(temp);
12655 kind = PyUnicode_KIND(temp);
12656 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012657 sign = 1;
12658 if (flags & F_ZERO)
12659 fill = '0';
12660 break;
12661
12662 case 'c':
12663 pbuf = formatbuf;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 kind = PyUnicode_4BYTE_KIND;
Victor Stinnerb9dcffb2011-09-29 00:39:24 +020012665 len = formatchar(pbuf, Py_ARRAY_LENGTH(formatbuf), v);
Benjamin Peterson29060642009-01-31 22:14:21 +000012666 if (len < 0)
12667 goto onError;
12668 break;
12669
12670 default:
12671 PyErr_Format(PyExc_ValueError,
12672 "unsupported format character '%c' (0x%x) "
12673 "at index %zd",
12674 (31<=c && c<=126) ? (char)c : '?',
12675 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000012677 goto onError;
12678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 /* pbuf is initialized here. */
12680 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000012681 if (sign) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682 if (PyUnicode_READ(kind, pbuf, pindex) == '-' ||
12683 PyUnicode_READ(kind, pbuf, pindex) == '+') {
12684 sign = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012685 len--;
12686 }
12687 else if (flags & F_SIGN)
12688 sign = '+';
12689 else if (flags & F_BLANK)
12690 sign = ' ';
12691 else
12692 sign = 0;
12693 }
12694 if (width < len)
12695 width = len;
12696 if (rescnt - (sign != 0) < width) {
12697 reslen -= rescnt;
12698 rescnt = width + fmtcnt + 100;
12699 reslen += rescnt;
12700 if (reslen < 0) {
12701 Py_XDECREF(temp);
12702 PyErr_NoMemory();
12703 goto onError;
12704 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012705 res0 = PyMem_Realloc(res0, reslen*sizeof(Py_UCS4));
12706 if (res0 == 0) {
12707 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +000012708 Py_XDECREF(temp);
12709 goto onError;
12710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 res = res0 + reslen - rescnt;
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 }
12713 if (sign) {
12714 if (fill != ' ')
12715 *res++ = sign;
12716 rescnt--;
12717 if (width > len)
12718 width--;
12719 }
12720 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12722 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000012723 if (fill != ' ') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12725 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012726 }
12727 rescnt -= 2;
12728 width -= 2;
12729 if (width < 0)
12730 width = 0;
12731 len -= 2;
12732 }
12733 if (width > len && !(flags & F_LJUST)) {
12734 do {
12735 --rescnt;
12736 *res++ = fill;
12737 } while (--width > len);
12738 }
12739 if (fill == ' ') {
12740 if (sign)
12741 *res++ = sign;
12742 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
12744 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
12745 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12746 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012747 }
12748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012749 /* Copy all characters, preserving len */
12750 len1 = len;
12751 while (len1--) {
12752 *res++ = PyUnicode_READ(kind, pbuf, pindex++);
12753 rescnt--;
12754 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012755 while (--width >= len) {
12756 --rescnt;
12757 *res++ = ' ';
12758 }
12759 if (dict && (argidx < arglen) && c != '%') {
12760 PyErr_SetString(PyExc_TypeError,
12761 "not all arguments converted during string formatting");
Thomas Woutersa96affe2006-03-12 00:29:36 +000012762 Py_XDECREF(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 goto onError;
12764 }
12765 Py_XDECREF(temp);
12766 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767 } /* until end */
12768 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 PyErr_SetString(PyExc_TypeError,
12770 "not all arguments converted during string formatting");
12771 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 }
12773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774
12775 for (max=0, res = res0; res < res0+reslen-rescnt; res++)
12776 if (*res > max)
12777 max = *res;
12778 result = PyUnicode_New(reslen - rescnt, max);
12779 if (!result)
Benjamin Peterson29060642009-01-31 22:14:21 +000012780 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 kind = PyUnicode_KIND(result);
12782 for (res = res0; res < res0+reslen-rescnt; res++)
12783 PyUnicode_WRITE(kind, PyUnicode_DATA(result), res-res0, *res);
12784 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012786 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787 }
12788 Py_DECREF(uformat);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789 return (PyObject *)result;
12790
Benjamin Peterson29060642009-01-31 22:14:21 +000012791 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012792 PyMem_Free(res0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012793 Py_DECREF(uformat);
12794 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012795 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796 }
12797 return NULL;
12798}
12799
Jeremy Hylton938ace62002-07-17 16:30:39 +000012800static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000012801unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
12802
Tim Peters6d6c1a32001-08-02 04:15:00 +000012803static PyObject *
12804unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12805{
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012807 static char *kwlist[] = {"object", "encoding", "errors", 0};
12808 char *encoding = NULL;
12809 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000012810
Benjamin Peterson14339b62009-01-31 16:36:08 +000012811 if (type != &PyUnicode_Type)
12812 return unicode_subtype_new(type, args, kwds);
12813 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000012814 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012815 return NULL;
12816 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012817 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012818 if (encoding == NULL && errors == NULL)
12819 return PyObject_Str(x);
12820 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012821 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000012822}
12823
Guido van Rossume023fe02001-08-30 03:12:59 +000012824static PyObject *
12825unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
12826{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012827 PyUnicodeObject *unicode, *self;
12828 Py_ssize_t length, char_size;
12829 int share_wstr, share_utf8;
12830 unsigned int kind;
12831 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000012832
Benjamin Peterson14339b62009-01-31 16:36:08 +000012833 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012834
12835 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
12836 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012837 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020012838 assert(_PyUnicode_CHECK(unicode));
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020012839 if (_PyUnicode_READY_REPLACE(&unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012840 return NULL;
12841
12842 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
12843 if (self == NULL) {
12844 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012845 return NULL;
12846 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012847 kind = PyUnicode_KIND(unicode);
12848 length = PyUnicode_GET_LENGTH(unicode);
12849
12850 _PyUnicode_LENGTH(self) = length;
12851 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
12852 _PyUnicode_STATE(self).interned = 0;
12853 _PyUnicode_STATE(self).kind = kind;
12854 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020012855 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012856 _PyUnicode_STATE(self).ready = 1;
12857 _PyUnicode_WSTR(self) = NULL;
12858 _PyUnicode_UTF8_LENGTH(self) = 0;
12859 _PyUnicode_UTF8(self) = NULL;
12860 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020012861 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012862
12863 share_utf8 = 0;
12864 share_wstr = 0;
12865 if (kind == PyUnicode_1BYTE_KIND) {
12866 char_size = 1;
12867 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
12868 share_utf8 = 1;
12869 }
12870 else if (kind == PyUnicode_2BYTE_KIND) {
12871 char_size = 2;
12872 if (sizeof(wchar_t) == 2)
12873 share_wstr = 1;
12874 }
12875 else {
12876 assert(kind == PyUnicode_4BYTE_KIND);
12877 char_size = 4;
12878 if (sizeof(wchar_t) == 4)
12879 share_wstr = 1;
12880 }
12881
12882 /* Ensure we won't overflow the length. */
12883 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
12884 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012886 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012887 data = PyObject_MALLOC((length + 1) * char_size);
12888 if (data == NULL) {
12889 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012890 goto onError;
12891 }
12892
Victor Stinnerc3c74152011-10-02 20:39:55 +020012893 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012894 if (share_utf8) {
12895 _PyUnicode_UTF8_LENGTH(self) = length;
12896 _PyUnicode_UTF8(self) = data;
12897 }
12898 if (share_wstr) {
12899 _PyUnicode_WSTR_LENGTH(self) = length;
12900 _PyUnicode_WSTR(self) = (wchar_t *)data;
12901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902
Victor Stinner07ac3eb2011-10-01 16:16:43 +020012903 Py_MEMCPY(data, PyUnicode_DATA(unicode),
12904 PyUnicode_KIND_SIZE(kind, length + 1));
12905 Py_DECREF(unicode);
12906 return (PyObject *)self;
12907
12908onError:
12909 Py_DECREF(unicode);
12910 Py_DECREF(self);
12911 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000012912}
12913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012914PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000012916\n\
Collin Winterd474ce82007-08-07 19:42:11 +000012917Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000012918encoding defaults to the current default string encoding.\n\
12919errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000012920
Guido van Rossum50e9fb92006-08-17 05:42:55 +000012921static PyObject *unicode_iter(PyObject *seq);
12922
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000012924 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012925 "str", /* tp_name */
12926 sizeof(PyUnicodeObject), /* tp_size */
12927 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012928 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012929 (destructor)unicode_dealloc, /* tp_dealloc */
12930 0, /* tp_print */
12931 0, /* tp_getattr */
12932 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000012933 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012934 unicode_repr, /* tp_repr */
12935 &unicode_as_number, /* tp_as_number */
12936 &unicode_as_sequence, /* tp_as_sequence */
12937 &unicode_as_mapping, /* tp_as_mapping */
12938 (hashfunc) unicode_hash, /* tp_hash*/
12939 0, /* tp_call*/
12940 (reprfunc) unicode_str, /* tp_str */
12941 PyObject_GenericGetAttr, /* tp_getattro */
12942 0, /* tp_setattro */
12943 0, /* tp_as_buffer */
12944 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000012945 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000012946 unicode_doc, /* tp_doc */
12947 0, /* tp_traverse */
12948 0, /* tp_clear */
12949 PyUnicode_RichCompare, /* tp_richcompare */
12950 0, /* tp_weaklistoffset */
12951 unicode_iter, /* tp_iter */
12952 0, /* tp_iternext */
12953 unicode_methods, /* tp_methods */
12954 0, /* tp_members */
12955 0, /* tp_getset */
12956 &PyBaseObject_Type, /* tp_base */
12957 0, /* tp_dict */
12958 0, /* tp_descr_get */
12959 0, /* tp_descr_set */
12960 0, /* tp_dictoffset */
12961 0, /* tp_init */
12962 0, /* tp_alloc */
12963 unicode_new, /* tp_new */
12964 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012965};
12966
12967/* Initialize the Unicode implementation */
12968
Thomas Wouters78890102000-07-22 19:25:51 +000012969void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012970{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012971 int i;
12972
Thomas Wouters477c8d52006-05-27 19:21:47 +000012973 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012974 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012975 0x000A, /* LINE FEED */
12976 0x000D, /* CARRIAGE RETURN */
12977 0x001C, /* FILE SEPARATOR */
12978 0x001D, /* GROUP SEPARATOR */
12979 0x001E, /* RECORD SEPARATOR */
12980 0x0085, /* NEXT LINE */
12981 0x2028, /* LINE SEPARATOR */
12982 0x2029, /* PARAGRAPH SEPARATOR */
12983 };
12984
Fred Drakee4315f52000-05-09 19:53:39 +000012985 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020012986 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012987 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012989
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000012990 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000012991 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000012992 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012993 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012994
12995 /* initialize the linebreak bloom filter */
12996 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020012998 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012999
13000 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001}
13002
13003/* Finalize the Unicode implementation */
13004
Christian Heimesa156e092008-02-16 07:38:31 +000013005int
13006PyUnicode_ClearFreeList(void)
13007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013009}
13010
Guido van Rossumd57fd912000-03-10 22:53:23 +000013011void
Thomas Wouters78890102000-07-22 19:25:51 +000013012_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013013{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013014 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013015
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013016 Py_XDECREF(unicode_empty);
13017 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013018
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013019 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013020 if (unicode_latin1[i]) {
13021 Py_DECREF(unicode_latin1[i]);
13022 unicode_latin1[i] = NULL;
13023 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013024 }
Christian Heimesa156e092008-02-16 07:38:31 +000013025 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013026}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013027
Walter Dörwald16807132007-05-25 13:52:07 +000013028void
13029PyUnicode_InternInPlace(PyObject **p)
13030{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013031 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13032 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013033#ifdef Py_DEBUG
13034 assert(s != NULL);
13035 assert(_PyUnicode_CHECK(s));
13036#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013037 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013038 return;
13039#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013040 /* If it's a subclass, we don't really know what putting
13041 it in the interned dict might do. */
13042 if (!PyUnicode_CheckExact(s))
13043 return;
13044 if (PyUnicode_CHECK_INTERNED(s))
13045 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013046 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner4fae54c2011-10-03 02:01:52 +020013047 assert(0 && "PyUnicode_READY fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013048 return;
13049 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013050 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013051 if (interned == NULL) {
13052 interned = PyDict_New();
13053 if (interned == NULL) {
13054 PyErr_Clear(); /* Don't leave an exception */
13055 return;
13056 }
13057 }
13058 /* It might be that the GetItem call fails even
13059 though the key is present in the dictionary,
13060 namely when this happens during a stack overflow. */
13061 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013062 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013063 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013064
Benjamin Peterson29060642009-01-31 22:14:21 +000013065 if (t) {
13066 Py_INCREF(t);
13067 Py_DECREF(*p);
13068 *p = t;
13069 return;
13070 }
Walter Dörwald16807132007-05-25 13:52:07 +000013071
Benjamin Peterson14339b62009-01-31 16:36:08 +000013072 PyThreadState_GET()->recursion_critical = 1;
13073 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13074 PyErr_Clear();
13075 PyThreadState_GET()->recursion_critical = 0;
13076 return;
13077 }
13078 PyThreadState_GET()->recursion_critical = 0;
13079 /* The two references in interned are not counted by refcnt.
13080 The deallocator will take care of this */
13081 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013082 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013083}
13084
13085void
13086PyUnicode_InternImmortal(PyObject **p)
13087{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13089
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090 PyUnicode_InternInPlace(p);
13091 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013093 Py_INCREF(*p);
13094 }
Walter Dörwald16807132007-05-25 13:52:07 +000013095}
13096
13097PyObject *
13098PyUnicode_InternFromString(const char *cp)
13099{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013100 PyObject *s = PyUnicode_FromString(cp);
13101 if (s == NULL)
13102 return NULL;
13103 PyUnicode_InternInPlace(&s);
13104 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013105}
13106
Alexander Belopolsky40018472011-02-26 01:02:56 +000013107void
13108_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013110 PyObject *keys;
13111 PyUnicodeObject *s;
13112 Py_ssize_t i, n;
13113 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013114
Benjamin Peterson14339b62009-01-31 16:36:08 +000013115 if (interned == NULL || !PyDict_Check(interned))
13116 return;
13117 keys = PyDict_Keys(interned);
13118 if (keys == NULL || !PyList_Check(keys)) {
13119 PyErr_Clear();
13120 return;
13121 }
Walter Dörwald16807132007-05-25 13:52:07 +000013122
Benjamin Peterson14339b62009-01-31 16:36:08 +000013123 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13124 detector, interned unicode strings are not forcibly deallocated;
13125 rather, we give them their stolen references back, and then clear
13126 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013127
Benjamin Peterson14339b62009-01-31 16:36:08 +000013128 n = PyList_GET_SIZE(keys);
13129 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013130 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013131 for (i = 0; i < n; i++) {
13132 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 if (PyUnicode_READY(s) == -1)
13134 fprintf(stderr, "could not ready string\n");
13135 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013136 case SSTATE_NOT_INTERNED:
13137 /* XXX Shouldn't happen */
13138 break;
13139 case SSTATE_INTERNED_IMMORTAL:
13140 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013141 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013142 break;
13143 case SSTATE_INTERNED_MORTAL:
13144 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013146 break;
13147 default:
13148 Py_FatalError("Inconsistent interned string state.");
13149 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013150 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013151 }
13152 fprintf(stderr, "total size of all interned strings: "
13153 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13154 "mortal/immortal\n", mortal_size, immortal_size);
13155 Py_DECREF(keys);
13156 PyDict_Clear(interned);
13157 Py_DECREF(interned);
13158 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013159}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013160
13161
13162/********************* Unicode Iterator **************************/
13163
13164typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013165 PyObject_HEAD
13166 Py_ssize_t it_index;
13167 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013168} unicodeiterobject;
13169
13170static void
13171unicodeiter_dealloc(unicodeiterobject *it)
13172{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013173 _PyObject_GC_UNTRACK(it);
13174 Py_XDECREF(it->it_seq);
13175 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013176}
13177
13178static int
13179unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13180{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013181 Py_VISIT(it->it_seq);
13182 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013183}
13184
13185static PyObject *
13186unicodeiter_next(unicodeiterobject *it)
13187{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013188 PyUnicodeObject *seq;
13189 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013190
Benjamin Peterson14339b62009-01-31 16:36:08 +000013191 assert(it != NULL);
13192 seq = it->it_seq;
13193 if (seq == NULL)
13194 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013195 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013197 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13198 int kind = PyUnicode_KIND(seq);
13199 void *data = PyUnicode_DATA(seq);
13200 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13201 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013202 if (item != NULL)
13203 ++it->it_index;
13204 return item;
13205 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013206
Benjamin Peterson14339b62009-01-31 16:36:08 +000013207 Py_DECREF(seq);
13208 it->it_seq = NULL;
13209 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013210}
13211
13212static PyObject *
13213unicodeiter_len(unicodeiterobject *it)
13214{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013215 Py_ssize_t len = 0;
13216 if (it->it_seq)
13217 len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
13218 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013219}
13220
13221PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13222
13223static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013224 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013225 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013226 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013227};
13228
13229PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013230 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13231 "str_iterator", /* tp_name */
13232 sizeof(unicodeiterobject), /* tp_basicsize */
13233 0, /* tp_itemsize */
13234 /* methods */
13235 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13236 0, /* tp_print */
13237 0, /* tp_getattr */
13238 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013239 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013240 0, /* tp_repr */
13241 0, /* tp_as_number */
13242 0, /* tp_as_sequence */
13243 0, /* tp_as_mapping */
13244 0, /* tp_hash */
13245 0, /* tp_call */
13246 0, /* tp_str */
13247 PyObject_GenericGetAttr, /* tp_getattro */
13248 0, /* tp_setattro */
13249 0, /* tp_as_buffer */
13250 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13251 0, /* tp_doc */
13252 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13253 0, /* tp_clear */
13254 0, /* tp_richcompare */
13255 0, /* tp_weaklistoffset */
13256 PyObject_SelfIter, /* tp_iter */
13257 (iternextfunc)unicodeiter_next, /* tp_iternext */
13258 unicodeiter_methods, /* tp_methods */
13259 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013260};
13261
13262static PyObject *
13263unicode_iter(PyObject *seq)
13264{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013265 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013266
Benjamin Peterson14339b62009-01-31 16:36:08 +000013267 if (!PyUnicode_Check(seq)) {
13268 PyErr_BadInternalCall();
13269 return NULL;
13270 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013271 if (PyUnicode_READY(seq) == -1)
13272 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013273 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13274 if (it == NULL)
13275 return NULL;
13276 it->it_index = 0;
13277 Py_INCREF(seq);
13278 it->it_seq = (PyUnicodeObject *)seq;
13279 _PyObject_GC_TRACK(it);
13280 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013281}
13282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013283#define UNIOP(x) Py_UNICODE_##x
13284#define UNIOP_t Py_UNICODE
13285#include "uniops.h"
13286#undef UNIOP
13287#undef UNIOP_t
13288#define UNIOP(x) Py_UCS4_##x
13289#define UNIOP_t Py_UCS4
13290#include "uniops.h"
13291#undef UNIOP
13292#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013293
Victor Stinner71133ff2010-09-01 23:43:53 +000013294Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013295PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013296{
13297 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
13298 Py_UNICODE *copy;
13299 Py_ssize_t size;
13300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013301 if (!PyUnicode_Check(unicode)) {
13302 PyErr_BadArgument();
13303 return NULL;
13304 }
Victor Stinner71133ff2010-09-01 23:43:53 +000013305 /* Ensure we won't overflow the size. */
13306 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13307 PyErr_NoMemory();
13308 return NULL;
13309 }
13310 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13311 size *= sizeof(Py_UNICODE);
13312 copy = PyMem_Malloc(size);
13313 if (copy == NULL) {
13314 PyErr_NoMemory();
13315 return NULL;
13316 }
13317 memcpy(copy, PyUnicode_AS_UNICODE(unicode), size);
13318 return copy;
13319}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013320
Georg Brandl66c221e2010-10-14 07:04:07 +000013321/* A _string module, to export formatter_parser and formatter_field_name_split
13322 to the string.Formatter class implemented in Python. */
13323
13324static PyMethodDef _string_methods[] = {
13325 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13326 METH_O, PyDoc_STR("split the argument as a field name")},
13327 {"formatter_parser", (PyCFunction) formatter_parser,
13328 METH_O, PyDoc_STR("parse the argument as a format string")},
13329 {NULL, NULL}
13330};
13331
13332static struct PyModuleDef _string_module = {
13333 PyModuleDef_HEAD_INIT,
13334 "_string",
13335 PyDoc_STR("string helper module"),
13336 0,
13337 _string_methods,
13338 NULL,
13339 NULL,
13340 NULL,
13341 NULL
13342};
13343
13344PyMODINIT_FUNC
13345PyInit__string(void)
13346{
13347 return PyModule_Create(&_string_module);
13348}
13349
13350
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013351#ifdef __cplusplus
13352}
13353#endif