blob: b2b492a9ec3e8569fc8cbe3f32acaa854b4910e9 [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
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Limit for the Unicode object free list */
54
Christian Heimes2202f872008-02-06 14:31:34 +000055#define PyUnicode_MAXFREELIST 1024
Guido van Rossumd57fd912000-03-10 22:53:23 +000056
57/* Limit for the Unicode object free list stay alive optimization.
58
59 The implementation will keep allocated Unicode memory intact for
60 all objects on the free list having a size less than this
Tim Petersced69f82003-09-16 20:30:58 +000061 limit. This reduces malloc() overhead for small Unicode objects.
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Christian Heimes2202f872008-02-06 14:31:34 +000063 At worst this will result in PyUnicode_MAXFREELIST *
Guido van Rossumfd4b9572000-04-10 13:51:10 +000064 (sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
Guido van Rossumd57fd912000-03-10 22:53:23 +000065 malloc()-overhead) bytes of unused garbage.
66
67 Setting the limit to 0 effectively turns the feature off.
68
Guido van Rossumfd4b9572000-04-10 13:51:10 +000069 Note: This is an experimental feature ! If you get core dumps when
70 using Unicode objects, turn this feature off.
Guido van Rossumd57fd912000-03-10 22:53:23 +000071
72*/
73
Guido van Rossumfd4b9572000-04-10 13:51:10 +000074#define KEEPALIVE_SIZE_LIMIT 9
Guido van Rossumd57fd912000-03-10 22:53:23 +000075
76/* Endianness switches; defaults to little endian */
77
78#ifdef WORDS_BIGENDIAN
79# define BYTEORDER_IS_BIG_ENDIAN
80#else
81# define BYTEORDER_IS_LITTLE_ENDIAN
82#endif
83
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000084/* --- Globals ------------------------------------------------------------
85
86 The globals are initialized by the _PyUnicode_Init() API and should
87 not be used before calling that API.
88
89*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091
92#ifdef __cplusplus
93extern "C" {
94#endif
95
Victor Stinner910337b2011-10-03 03:20:16 +020096#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020097# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020098#else
99# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
100#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200101
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102#define _PyUnicode_UTF8(op) \
103 (((PyCompactUnicodeObject*)(op))->utf8)
104#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200105 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200106 assert(PyUnicode_IS_READY(op)), \
107 PyUnicode_IS_COMPACT_ASCII(op) ? \
108 ((char*)((PyASCIIObject*)(op) + 1)) : \
109 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200110#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200111 (((PyCompactUnicodeObject*)(op))->utf8_length)
112#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200113 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200114 assert(PyUnicode_IS_READY(op)), \
115 PyUnicode_IS_COMPACT_ASCII(op) ? \
116 ((PyASCIIObject*)(op))->length : \
117 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200118#define _PyUnicode_WSTR(op) \
119 (((PyASCIIObject*)(op))->wstr)
120#define _PyUnicode_WSTR_LENGTH(op) \
121 (((PyCompactUnicodeObject*)(op))->wstr_length)
122#define _PyUnicode_LENGTH(op) \
123 (((PyASCIIObject *)(op))->length)
124#define _PyUnicode_STATE(op) \
125 (((PyASCIIObject *)(op))->state)
126#define _PyUnicode_HASH(op) \
127 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200128#define _PyUnicode_KIND(op) \
129 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200130 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_GET_LENGTH(op) \
132 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200133 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200134#define _PyUnicode_DATA_ANY(op) \
135 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200136
Victor Stinner910337b2011-10-03 03:20:16 +0200137#undef PyUnicode_READY
138#define PyUnicode_READY(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200141 0 : \
142 _PyUnicode_Ready((PyObject *)(op))))
Victor Stinner910337b2011-10-03 03:20:16 +0200143
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200144#define _PyUnicode_READY_REPLACE(p_obj) \
145 (assert(_PyUnicode_CHECK(*p_obj)), \
146 (PyUnicode_IS_READY(*p_obj) ? \
147 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
148
Victor Stinnerc379ead2011-10-03 12:52:27 +0200149#define _PyUnicode_SHARE_UTF8(op) \
150 (assert(_PyUnicode_CHECK(op)), \
151 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
152 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
153#define _PyUnicode_SHARE_WSTR(op) \
154 (assert(_PyUnicode_CHECK(op)), \
155 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
156
Victor Stinner829c0ad2011-10-03 01:08:02 +0200157/* true if the Unicode object has an allocated UTF-8 memory block
158 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200159#define _PyUnicode_HAS_UTF8_MEMORY(op) \
160 (assert(_PyUnicode_CHECK(op)), \
161 (!PyUnicode_IS_COMPACT_ASCII(op) \
162 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200163 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
164
Victor Stinner03490912011-10-03 23:45:12 +0200165/* true if the Unicode object has an allocated wstr memory block
166 (not shared with other data) */
167#define _PyUnicode_HAS_WSTR_MEMORY(op) \
168 (assert(_PyUnicode_CHECK(op)), \
169 (_PyUnicode_WSTR(op) && \
170 (!PyUnicode_IS_READY(op) || \
171 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
172
Victor Stinner910337b2011-10-03 03:20:16 +0200173/* Generic helper macro to convert characters of different types.
174 from_type and to_type have to be valid type names, begin and end
175 are pointers to the source characters which should be of type
176 "from_type *". to is a pointer of type "to_type *" and points to the
177 buffer where the result characters are written to. */
178#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
179 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200180 to_type *_to = (to_type *) to; \
181 const from_type *_iter = (begin); \
182 const from_type *_end = (end); \
183 Py_ssize_t n = (_end) - (_iter); \
184 const from_type *_unrolled_end = \
185 _iter + (n & ~ (Py_ssize_t) 3); \
186 while (_iter < (_unrolled_end)) { \
187 _to[0] = (to_type) _iter[0]; \
188 _to[1] = (to_type) _iter[1]; \
189 _to[2] = (to_type) _iter[2]; \
190 _to[3] = (to_type) _iter[3]; \
191 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200192 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200193 while (_iter < (_end)) \
194 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200195 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200196
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200197/* The Unicode string has been modified: reset the hash */
198#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
199
Walter Dörwald16807132007-05-25 13:52:07 +0000200/* This dictionary holds all interned unicode strings. Note that references
201 to strings in this dictionary are *not* counted in the string's ob_refcnt.
202 When the interned string reaches a refcnt of 0 the string deallocation
203 function will delete the reference from this dictionary.
204
205 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000206 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000207*/
208static PyObject *interned;
209
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000210/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200211static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000212
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200213/* List of static strings. */
214static _Py_Identifier *static_strings;
215
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216/* Single character Unicode strings in the Latin-1 range are being
217 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200218static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000219
Christian Heimes190d79e2008-01-30 11:58:22 +0000220/* Fast detection of the most frequent whitespace characters */
221const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000223/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000225/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000226/* case 0x000C: * FORM FEED */
227/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000228 0, 1, 1, 1, 1, 1, 0, 0,
229 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000230/* case 0x001C: * FILE SEPARATOR */
231/* case 0x001D: * GROUP SEPARATOR */
232/* case 0x001E: * RECORD SEPARATOR */
233/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000234 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000235/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000236 1, 0, 0, 0, 0, 0, 0, 0,
237 0, 0, 0, 0, 0, 0, 0, 0,
238 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000240
Benjamin Peterson14339b62009-01-31 16:36:08 +0000241 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0,
245 0, 0, 0, 0, 0, 0, 0, 0,
246 0, 0, 0, 0, 0, 0, 0, 0,
247 0, 0, 0, 0, 0, 0, 0, 0,
248 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000249};
250
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200251/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200252static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200253static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200254static void copy_characters(
255 PyObject *to, Py_ssize_t to_start,
256 PyObject *from, Py_ssize_t from_start,
257 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200258#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200259static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200260#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200261
Alexander Belopolsky40018472011-02-26 01:02:56 +0000262static PyObject *
263unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000264 PyObject **errorHandler,const char *encoding, const char *reason,
265 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
266 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
267
Alexander Belopolsky40018472011-02-26 01:02:56 +0000268static void
269raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300270 const char *encoding,
271 const Py_UNICODE *unicode, Py_ssize_t size,
272 Py_ssize_t startpos, Py_ssize_t endpos,
273 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000274
Christian Heimes190d79e2008-01-30 11:58:22 +0000275/* Same for linebreaks */
276static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000278/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000279/* 0x000B, * LINE TABULATION */
280/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000281/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000282 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000284/* 0x001C, * FILE SEPARATOR */
285/* 0x001D, * GROUP SEPARATOR */
286/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 0, 0, 0, 0, 1, 1, 1, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000292
Benjamin Peterson14339b62009-01-31 16:36:08 +0000293 0, 0, 0, 0, 0, 0, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0,
300 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000301};
302
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300303/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
304 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000305Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000306PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000307{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000308#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000309 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000310#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000311 /* This is actually an illegal character, so it should
312 not be passed to unichr. */
313 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000314#endif
315}
316
Victor Stinner910337b2011-10-03 03:20:16 +0200317#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200318int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200319/* FIXME: use PyObject* type for op */
320_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200321{
322 PyASCIIObject *ascii;
323 unsigned int kind;
324
325 assert(PyUnicode_Check(op));
326
327 ascii = (PyASCIIObject *)op;
328 kind = ascii->state.kind;
329
Victor Stinnera3b334d2011-10-03 13:53:37 +0200330 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(ascii->state.ready == 1);
333 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200335 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200336 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200337
Victor Stinnera41463c2011-10-04 01:05:08 +0200338 if (ascii->state.compact == 1) {
339 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200340 assert(kind == PyUnicode_1BYTE_KIND
341 || kind == PyUnicode_2BYTE_KIND
342 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200344 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200345 assert (compact->utf8 != data);
346 } else {
347 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
348
349 data = unicode->data.any;
350 if (kind == PyUnicode_WCHAR_KIND) {
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ascii == 0);
353 assert(ascii->state.ready == 0);
354 assert(ascii->wstr != NULL);
355 assert(data == NULL);
356 assert(compact->utf8 == NULL);
357 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
358 }
359 else {
360 assert(kind == PyUnicode_1BYTE_KIND
361 || kind == PyUnicode_2BYTE_KIND
362 || kind == PyUnicode_4BYTE_KIND);
363 assert(ascii->state.compact == 0);
364 assert(ascii->state.ready == 1);
365 assert(data != NULL);
366 if (ascii->state.ascii) {
367 assert (compact->utf8 == data);
368 assert (compact->utf8_length == ascii->length);
369 }
370 else
371 assert (compact->utf8 != data);
372 }
373 }
374 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200375 if (
376#if SIZEOF_WCHAR_T == 2
377 kind == PyUnicode_2BYTE_KIND
378#else
379 kind == PyUnicode_4BYTE_KIND
380#endif
381 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200382 {
383 assert(ascii->wstr == data);
384 assert(compact->wstr_length == ascii->length);
385 } else
386 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200387 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200388
389 if (compact->utf8 == NULL)
390 assert(compact->utf8_length == 0);
391 if (ascii->wstr == NULL)
392 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200393 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 /* check that the best kind is used */
395 if (check_content && kind != PyUnicode_WCHAR_KIND)
396 {
397 Py_ssize_t i;
398 Py_UCS4 maxchar = 0;
399 void *data = PyUnicode_DATA(ascii);
400 for (i=0; i < ascii->length; i++)
401 {
402 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
403 if (ch > maxchar)
404 maxchar = ch;
405 }
406 if (kind == PyUnicode_1BYTE_KIND) {
407 if (ascii->state.ascii == 0)
408 assert(maxchar >= 128);
409 else
410 assert(maxchar < 128);
411 }
412 else if (kind == PyUnicode_2BYTE_KIND)
413 assert(maxchar >= 0x100);
414 else
415 assert(maxchar >= 0x10000);
416 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200417 if (check_content && !unicode_is_singleton((PyObject*)ascii))
418 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Thomas Wouters477c8d52006-05-27 19:21:47 +0000423/* --- Bloom Filters ----------------------------------------------------- */
424
425/* stuff to implement simple "bloom filters" for Unicode characters.
426 to keep things simple, we use a single bitmask, using the least 5
427 bits from each unicode characters as the bit index. */
428
429/* the linebreak mask is set up by Unicode_Init below */
430
Antoine Pitrouf068f942010-01-13 14:19:12 +0000431#if LONG_BIT >= 128
432#define BLOOM_WIDTH 128
433#elif LONG_BIT >= 64
434#define BLOOM_WIDTH 64
435#elif LONG_BIT >= 32
436#define BLOOM_WIDTH 32
437#else
438#error "LONG_BIT is smaller than 32"
439#endif
440
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441#define BLOOM_MASK unsigned long
442
443static BLOOM_MASK bloom_linebreak;
444
Antoine Pitrouf068f942010-01-13 14:19:12 +0000445#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
446#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Benjamin Peterson29060642009-01-31 22:14:21 +0000448#define BLOOM_LINEBREAK(ch) \
449 ((ch) < 128U ? ascii_linebreak[(ch)] : \
450 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451
Alexander Belopolsky40018472011-02-26 01:02:56 +0000452Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200453make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454{
455 /* calculate simple bloom-style bitmask for a given unicode string */
456
Antoine Pitrouf068f942010-01-13 14:19:12 +0000457 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458 Py_ssize_t i;
459
460 mask = 0;
461 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463
464 return mask;
465}
466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200467#define BLOOM_MEMBER(mask, chr, str) \
468 (BLOOM(mask, chr) \
469 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470
Guido van Rossumd57fd912000-03-10 22:53:23 +0000471/* --- Unicode Object ----------------------------------------------------- */
472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200473static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200474fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200475
476Py_LOCAL_INLINE(char *) findchar(void *s, int kind,
477 Py_ssize_t size, Py_UCS4 ch,
478 int direction)
479{
480 /* like wcschr, but doesn't stop at NULL characters */
481 Py_ssize_t i;
482 if (direction == 1) {
483 for(i = 0; i < size; i++)
484 if (PyUnicode_READ(kind, s, i) == ch)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200485 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200486 }
487 else {
488 for(i = size-1; i >= 0; i--)
489 if (PyUnicode_READ(kind, s, i) == ch)
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200490 return (char*)s + kind * i;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200491 }
492 return NULL;
493}
494
Victor Stinnerfe226c02011-10-03 03:52:20 +0200495static PyObject*
496resize_compact(PyObject *unicode, Py_ssize_t length)
497{
498 Py_ssize_t char_size;
499 Py_ssize_t struct_size;
500 Py_ssize_t new_size;
501 int share_wstr;
502
503 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200504 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200505 if (PyUnicode_IS_COMPACT_ASCII(unicode))
506 struct_size = sizeof(PyASCIIObject);
507 else
508 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200509 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200510
511 _Py_DEC_REFTOTAL;
512 _Py_ForgetReference(unicode);
513
514 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
515 PyErr_NoMemory();
516 return NULL;
517 }
518 new_size = (struct_size + (length + 1) * char_size);
519
520 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
521 if (unicode == NULL) {
522 PyObject_Del(unicode);
523 PyErr_NoMemory();
524 return NULL;
525 }
526 _Py_NewReference(unicode);
527 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200528 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200529 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200530 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
531 _PyUnicode_WSTR_LENGTH(unicode) = length;
532 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200533 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
534 length, 0);
535 return unicode;
536}
537
Alexander Belopolsky40018472011-02-26 01:02:56 +0000538static int
Victor Stinner95663112011-10-04 01:03:50 +0200539resize_inplace(PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000540{
Victor Stinner95663112011-10-04 01:03:50 +0200541 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200542 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200543 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000544
Victor Stinner95663112011-10-04 01:03:50 +0200545 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546
547 if (PyUnicode_IS_READY(unicode)) {
548 Py_ssize_t char_size;
549 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200550 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200551 void *data;
552
553 data = _PyUnicode_DATA_ANY(unicode);
554 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200556 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
557 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200558 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
559 {
560 PyObject_DEL(_PyUnicode_UTF8(unicode));
561 _PyUnicode_UTF8(unicode) = NULL;
562 _PyUnicode_UTF8_LENGTH(unicode) = 0;
563 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200564
565 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
566 PyErr_NoMemory();
567 return -1;
568 }
569 new_size = (length + 1) * char_size;
570
571 data = (PyObject *)PyObject_REALLOC(data, new_size);
572 if (data == NULL) {
573 PyErr_NoMemory();
574 return -1;
575 }
576 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200577 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 _PyUnicode_WSTR_LENGTH(unicode) = length;
580 }
581 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200582 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200583 _PyUnicode_UTF8_LENGTH(unicode) = length;
584 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200585 _PyUnicode_LENGTH(unicode) = length;
586 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200587 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200588 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200589 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200590 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200591 }
Victor Stinner95663112011-10-04 01:03:50 +0200592 assert(_PyUnicode_WSTR(unicode) != NULL);
593
594 /* check for integer overflow */
595 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
596 PyErr_NoMemory();
597 return -1;
598 }
599 wstr = _PyUnicode_WSTR(unicode);
600 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
601 if (!wstr) {
602 PyErr_NoMemory();
603 return -1;
604 }
605 _PyUnicode_WSTR(unicode) = wstr;
606 _PyUnicode_WSTR(unicode)[length] = 0;
607 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200608 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000609 return 0;
610}
611
Victor Stinnerfe226c02011-10-03 03:52:20 +0200612static PyObject*
613resize_copy(PyObject *unicode, Py_ssize_t length)
614{
615 Py_ssize_t copy_length;
616 if (PyUnicode_IS_COMPACT(unicode)) {
617 PyObject *copy;
618 assert(PyUnicode_IS_READY(unicode));
619
620 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
621 if (copy == NULL)
622 return NULL;
623
624 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200625 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200626 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200627 }
628 else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200629 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200630 assert(_PyUnicode_WSTR(unicode) != NULL);
631 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200632 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633 if (w == NULL)
634 return NULL;
635 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
636 copy_length = Py_MIN(copy_length, length);
637 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
638 copy_length);
639 return (PyObject*)w;
640 }
641}
642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000644 Ux0000 terminated; some code (e.g. new_identifier)
645 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000646
647 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000648 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000649
650*/
651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200652#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200653static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200654#endif
655
Alexander Belopolsky40018472011-02-26 01:02:56 +0000656static PyUnicodeObject *
657_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658{
659 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200660 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000661
Thomas Wouters477c8d52006-05-27 19:21:47 +0000662 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000663 if (length == 0 && unicode_empty != NULL) {
664 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200665 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000666 }
667
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000668 /* Ensure we won't overflow the size. */
669 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
670 return (PyUnicodeObject *)PyErr_NoMemory();
671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200672 if (length < 0) {
673 PyErr_SetString(PyExc_SystemError,
674 "Negative size passed to _PyUnicode_New");
675 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000676 }
677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200678#ifdef Py_DEBUG
679 ++unicode_old_new_calls;
680#endif
681
682 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
683 if (unicode == NULL)
684 return NULL;
685 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
686 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
687 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000688 PyErr_NoMemory();
689 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200691
Jeremy Hyltond8082792003-09-16 19:41:39 +0000692 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000693 * the caller fails before initializing str -- unicode_resize()
694 * reads str[0], and the Keep-Alive optimization can keep memory
695 * allocated for str alive across a call to unicode_dealloc(unicode).
696 * We don't want unicode_resize to read uninitialized memory in
697 * that case.
698 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200699 _PyUnicode_WSTR(unicode)[0] = 0;
700 _PyUnicode_WSTR(unicode)[length] = 0;
701 _PyUnicode_WSTR_LENGTH(unicode) = length;
702 _PyUnicode_HASH(unicode) = -1;
703 _PyUnicode_STATE(unicode).interned = 0;
704 _PyUnicode_STATE(unicode).kind = 0;
705 _PyUnicode_STATE(unicode).compact = 0;
706 _PyUnicode_STATE(unicode).ready = 0;
707 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200708 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200710 _PyUnicode_UTF8(unicode) = NULL;
711 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000713
Benjamin Peterson29060642009-01-31 22:14:21 +0000714 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000715 /* XXX UNREF/NEWREF interface should be more symmetrical */
716 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000717 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000718 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720}
721
Victor Stinnerf42dc442011-10-02 23:33:16 +0200722static const char*
723unicode_kind_name(PyObject *unicode)
724{
Victor Stinner42dfd712011-10-03 14:41:45 +0200725 /* don't check consistency: unicode_kind_name() is called from
726 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200727 if (!PyUnicode_IS_COMPACT(unicode))
728 {
729 if (!PyUnicode_IS_READY(unicode))
730 return "wstr";
731 switch(PyUnicode_KIND(unicode))
732 {
733 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200734 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200735 return "legacy ascii";
736 else
737 return "legacy latin1";
738 case PyUnicode_2BYTE_KIND:
739 return "legacy UCS2";
740 case PyUnicode_4BYTE_KIND:
741 return "legacy UCS4";
742 default:
743 return "<legacy invalid kind>";
744 }
745 }
746 assert(PyUnicode_IS_READY(unicode));
747 switch(PyUnicode_KIND(unicode))
748 {
749 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200750 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200751 return "ascii";
752 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200753 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200754 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200755 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200756 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200757 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200758 default:
759 return "<invalid compact kind>";
760 }
761}
762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200764static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200765
766/* Functions wrapping macros for use in debugger */
767char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200768 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200769}
770
771void *_PyUnicode_compact_data(void *unicode) {
772 return _PyUnicode_COMPACT_DATA(unicode);
773}
774void *_PyUnicode_data(void *unicode){
775 printf("obj %p\n", unicode);
776 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
777 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
778 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
779 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
780 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
781 return PyUnicode_DATA(unicode);
782}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200783
784void
785_PyUnicode_Dump(PyObject *op)
786{
787 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200788 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
789 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
790 void *data;
791 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
792 if (ascii->state.compact)
793 data = (compact + 1);
794 else
795 data = unicode->data.any;
796 if (ascii->wstr == data)
797 printf("shared ");
798 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200799 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200800 printf(" (%zu), ", compact->wstr_length);
801 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
802 printf("shared ");
803 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200804 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200805 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200806}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200807#endif
808
809PyObject *
810PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
811{
812 PyObject *obj;
813 PyCompactUnicodeObject *unicode;
814 void *data;
815 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200816 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817 Py_ssize_t char_size;
818 Py_ssize_t struct_size;
819
820 /* Optimization for empty strings */
821 if (size == 0 && unicode_empty != NULL) {
822 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200823 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200824 }
825
826#ifdef Py_DEBUG
827 ++unicode_new_new_calls;
828#endif
829
Victor Stinner9e9d6892011-10-04 01:02:02 +0200830 is_ascii = 0;
831 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200832 struct_size = sizeof(PyCompactUnicodeObject);
833 if (maxchar < 128) {
834 kind_state = PyUnicode_1BYTE_KIND;
835 char_size = 1;
836 is_ascii = 1;
837 struct_size = sizeof(PyASCIIObject);
838 }
839 else if (maxchar < 256) {
840 kind_state = PyUnicode_1BYTE_KIND;
841 char_size = 1;
842 }
843 else if (maxchar < 65536) {
844 kind_state = PyUnicode_2BYTE_KIND;
845 char_size = 2;
846 if (sizeof(wchar_t) == 2)
847 is_sharing = 1;
848 }
849 else {
850 kind_state = PyUnicode_4BYTE_KIND;
851 char_size = 4;
852 if (sizeof(wchar_t) == 4)
853 is_sharing = 1;
854 }
855
856 /* Ensure we won't overflow the size. */
857 if (size < 0) {
858 PyErr_SetString(PyExc_SystemError,
859 "Negative size passed to PyUnicode_New");
860 return NULL;
861 }
862 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
863 return PyErr_NoMemory();
864
865 /* Duplicated allocation code from _PyObject_New() instead of a call to
866 * PyObject_New() so we are able to allocate space for the object and
867 * it's data buffer.
868 */
869 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
870 if (obj == NULL)
871 return PyErr_NoMemory();
872 obj = PyObject_INIT(obj, &PyUnicode_Type);
873 if (obj == NULL)
874 return NULL;
875
876 unicode = (PyCompactUnicodeObject *)obj;
877 if (is_ascii)
878 data = ((PyASCIIObject*)obj) + 1;
879 else
880 data = unicode + 1;
881 _PyUnicode_LENGTH(unicode) = size;
882 _PyUnicode_HASH(unicode) = -1;
883 _PyUnicode_STATE(unicode).interned = 0;
884 _PyUnicode_STATE(unicode).kind = kind_state;
885 _PyUnicode_STATE(unicode).compact = 1;
886 _PyUnicode_STATE(unicode).ready = 1;
887 _PyUnicode_STATE(unicode).ascii = is_ascii;
888 if (is_ascii) {
889 ((char*)data)[size] = 0;
890 _PyUnicode_WSTR(unicode) = NULL;
891 }
892 else if (kind_state == PyUnicode_1BYTE_KIND) {
893 ((char*)data)[size] = 0;
894 _PyUnicode_WSTR(unicode) = NULL;
895 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200897 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200898 }
899 else {
900 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200901 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200902 if (kind_state == PyUnicode_2BYTE_KIND)
903 ((Py_UCS2*)data)[size] = 0;
904 else /* kind_state == PyUnicode_4BYTE_KIND */
905 ((Py_UCS4*)data)[size] = 0;
906 if (is_sharing) {
907 _PyUnicode_WSTR_LENGTH(unicode) = size;
908 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
909 }
910 else {
911 _PyUnicode_WSTR_LENGTH(unicode) = 0;
912 _PyUnicode_WSTR(unicode) = NULL;
913 }
914 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200915 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200916 return obj;
917}
918
919#if SIZEOF_WCHAR_T == 2
920/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
921 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200922 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
924 This function assumes that unicode can hold one more code point than wstr
925 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200926static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
928 PyUnicodeObject *unicode)
929{
930 const wchar_t *iter;
931 Py_UCS4 *ucs4_out;
932
Victor Stinner910337b2011-10-03 03:20:16 +0200933 assert(unicode != NULL);
934 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200935 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
936 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
937
938 for (iter = begin; iter < end; ) {
939 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
940 _PyUnicode_GET_LENGTH(unicode)));
941 if (*iter >= 0xD800 && *iter <= 0xDBFF
942 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
943 {
944 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
945 iter += 2;
946 }
947 else {
948 *ucs4_out++ = *iter;
949 iter++;
950 }
951 }
952 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
953 _PyUnicode_GET_LENGTH(unicode)));
954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200955}
956#endif
957
Victor Stinnercd9950f2011-10-02 00:34:53 +0200958static int
959_PyUnicode_Dirty(PyObject *unicode)
960{
Victor Stinner910337b2011-10-03 03:20:16 +0200961 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +0200962 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +0200963 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +0200964 "Cannot modify a string having more than 1 reference");
965 return -1;
966 }
967 _PyUnicode_DIRTY(unicode);
968 return 0;
969}
970
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200971static int
972_copy_characters(PyObject *to, Py_ssize_t to_start,
973 PyObject *from, Py_ssize_t from_start,
974 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975{
Victor Stinnera0702ab2011-09-29 14:14:38 +0200976 unsigned int from_kind, to_kind;
977 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200978 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200980 assert(PyUnicode_Check(from));
981 assert(PyUnicode_Check(to));
982 assert(PyUnicode_IS_READY(from));
983 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200984
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200985 assert(PyUnicode_GET_LENGTH(from) >= how_many);
986 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
987 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200988
Victor Stinnerf5ca1a22011-09-28 23:54:59 +0200989 if (how_many == 0)
990 return 0;
991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200993 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +0200995 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200996
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200997#ifdef Py_DEBUG
998 if (!check_maxchar
999 && (from_kind > to_kind
1000 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001001 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001002 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1003 Py_UCS4 ch;
1004 Py_ssize_t i;
1005 for (i=0; i < how_many; i++) {
1006 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1007 assert(ch <= to_maxchar);
1008 }
1009 }
1010#endif
1011 fast = (from_kind == to_kind);
1012 if (check_maxchar
1013 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1014 {
1015 /* deny latin1 => ascii */
1016 fast = 0;
1017 }
1018
1019 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001020 Py_MEMCPY((char*)to_data + to_kind * to_start,
1021 (char*)from_data + from_kind * from_start,
1022 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001023 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001024 else if (from_kind == PyUnicode_1BYTE_KIND
1025 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001026 {
1027 _PyUnicode_CONVERT_BYTES(
1028 Py_UCS1, Py_UCS2,
1029 PyUnicode_1BYTE_DATA(from) + from_start,
1030 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1031 PyUnicode_2BYTE_DATA(to) + to_start
1032 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001033 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001034 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001035 && to_kind == PyUnicode_4BYTE_KIND)
1036 {
1037 _PyUnicode_CONVERT_BYTES(
1038 Py_UCS1, Py_UCS4,
1039 PyUnicode_1BYTE_DATA(from) + from_start,
1040 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1041 PyUnicode_4BYTE_DATA(to) + to_start
1042 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001043 }
1044 else if (from_kind == PyUnicode_2BYTE_KIND
1045 && to_kind == PyUnicode_4BYTE_KIND)
1046 {
1047 _PyUnicode_CONVERT_BYTES(
1048 Py_UCS2, Py_UCS4,
1049 PyUnicode_2BYTE_DATA(from) + from_start,
1050 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1051 PyUnicode_4BYTE_DATA(to) + to_start
1052 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001053 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001054 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001055 /* check if max_char(from substring) <= max_char(to) */
1056 if (from_kind > to_kind
1057 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001058 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001059 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001060 /* slow path to check for character overflow */
1061 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001063 Py_ssize_t i;
1064
Victor Stinner56c161a2011-10-06 02:47:11 +02001065#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001066 for (i=0; i < how_many; i++) {
1067 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001068 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001069 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1070 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001071#else
1072 if (!check_maxchar) {
1073 for (i=0; i < how_many; i++) {
1074 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1075 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1076 }
1077 }
1078 else {
1079 for (i=0; i < how_many; i++) {
1080 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1081 if (ch > to_maxchar)
1082 return 1;
1083 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1084 }
1085 }
1086#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001087 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001088 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001089 assert(0 && "inconsistent state");
1090 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001091 }
1092 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001093 return 0;
1094}
1095
1096static void
1097copy_characters(PyObject *to, Py_ssize_t to_start,
1098 PyObject *from, Py_ssize_t from_start,
1099 Py_ssize_t how_many)
1100{
1101 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1102}
1103
1104Py_ssize_t
1105PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1106 PyObject *from, Py_ssize_t from_start,
1107 Py_ssize_t how_many)
1108{
1109 int err;
1110
1111 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1112 PyErr_BadInternalCall();
1113 return -1;
1114 }
1115
1116 if (PyUnicode_READY(from))
1117 return -1;
1118 if (PyUnicode_READY(to))
1119 return -1;
1120
1121 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1122 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1123 PyErr_Format(PyExc_SystemError,
1124 "Cannot write %zi characters at %zi "
1125 "in a string of %zi characters",
1126 how_many, to_start, PyUnicode_GET_LENGTH(to));
1127 return -1;
1128 }
1129
1130 if (how_many == 0)
1131 return 0;
1132
1133 if (_PyUnicode_Dirty(to))
1134 return -1;
1135
1136 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1137 if (err) {
1138 PyErr_Format(PyExc_SystemError,
1139 "Cannot copy %s characters "
1140 "into a string of %s characters",
1141 unicode_kind_name(from),
1142 unicode_kind_name(to));
1143 return -1;
1144 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146}
1147
Victor Stinner17222162011-09-28 22:15:37 +02001148/* Find the maximum code point and count the number of surrogate pairs so a
1149 correct string length can be computed before converting a string to UCS4.
1150 This function counts single surrogates as a character and not as a pair.
1151
1152 Return 0 on success, or -1 on error. */
1153static int
1154find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1155 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
1157 const wchar_t *iter;
1158
Victor Stinnerc53be962011-10-02 21:33:54 +02001159 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001160 *num_surrogates = 0;
1161 *maxchar = 0;
1162
1163 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001164 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001165 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001166#if SIZEOF_WCHAR_T != 2
1167 if (*maxchar >= 0x10000)
1168 return 0;
1169#endif
1170 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171#if SIZEOF_WCHAR_T == 2
1172 if (*iter >= 0xD800 && *iter <= 0xDBFF
1173 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1174 {
1175 Py_UCS4 surrogate_val;
1176 surrogate_val = (((iter[0] & 0x3FF)<<10)
1177 | (iter[1] & 0x3FF)) + 0x10000;
1178 ++(*num_surrogates);
1179 if (surrogate_val > *maxchar)
1180 *maxchar = surrogate_val;
1181 iter += 2;
1182 }
1183 else
1184 iter++;
1185#else
1186 iter++;
1187#endif
1188 }
1189 return 0;
1190}
1191
1192#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001193static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194#endif
1195
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001196static int
1197unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001198{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001199 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200 wchar_t *end;
1201 Py_UCS4 maxchar = 0;
1202 Py_ssize_t num_surrogates;
1203#if SIZEOF_WCHAR_T == 2
1204 Py_ssize_t length_wo_surrogates;
1205#endif
1206
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001207 assert(p_obj != NULL);
1208 unicode = (PyUnicodeObject *)*p_obj;
1209
Georg Brandl7597add2011-10-05 16:36:47 +02001210 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001211 strings were created using _PyObject_New() and where no canonical
1212 representation (the str field) has been set yet aka strings
1213 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001214 assert(_PyUnicode_CHECK(unicode));
1215 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001217 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001218 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001219 /* Actually, it should neither be interned nor be anything else: */
1220 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221
1222#ifdef Py_DEBUG
1223 ++unicode_ready_calls;
1224#endif
1225
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001226#ifdef Py_DEBUG
1227 assert(!replace || Py_REFCNT(unicode) == 1);
1228#else
1229 if (replace && Py_REFCNT(unicode) != 1)
1230 replace = 0;
1231#endif
1232 if (replace) {
1233 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1234 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1235 /* Optimization for empty strings */
1236 if (len == 0) {
1237 Py_INCREF(unicode_empty);
1238 Py_DECREF(*p_obj);
1239 *p_obj = unicode_empty;
1240 return 0;
1241 }
1242 if (len == 1 && wstr[0] < 256) {
1243 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1244 if (latin1_char == NULL)
1245 return -1;
1246 Py_DECREF(*p_obj);
1247 *p_obj = latin1_char;
1248 return 0;
1249 }
1250 }
1251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001253 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001254 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001255 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001256
1257 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001258 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1259 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 PyErr_NoMemory();
1261 return -1;
1262 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001263 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 _PyUnicode_WSTR(unicode), end,
1265 PyUnicode_1BYTE_DATA(unicode));
1266 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1267 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1268 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1269 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001270 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001271 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001272 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001273 }
1274 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001275 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001276 _PyUnicode_UTF8(unicode) = NULL;
1277 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001278 }
1279 PyObject_FREE(_PyUnicode_WSTR(unicode));
1280 _PyUnicode_WSTR(unicode) = NULL;
1281 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1282 }
1283 /* In this case we might have to convert down from 4-byte native
1284 wchar_t to 2-byte unicode. */
1285 else if (maxchar < 65536) {
1286 assert(num_surrogates == 0 &&
1287 "FindMaxCharAndNumSurrogatePairs() messed up");
1288
Victor Stinner506f5922011-09-28 22:34:18 +02001289#if SIZEOF_WCHAR_T == 2
1290 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001291 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001292 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1293 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1294 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001295 _PyUnicode_UTF8(unicode) = NULL;
1296 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001297#else
1298 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001299 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001300 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001301 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001302 PyErr_NoMemory();
1303 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 }
Victor Stinner506f5922011-09-28 22:34:18 +02001305 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1306 _PyUnicode_WSTR(unicode), end,
1307 PyUnicode_2BYTE_DATA(unicode));
1308 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1309 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1310 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001311 _PyUnicode_UTF8(unicode) = NULL;
1312 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001313 PyObject_FREE(_PyUnicode_WSTR(unicode));
1314 _PyUnicode_WSTR(unicode) = NULL;
1315 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1316#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001317 }
1318 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1319 else {
1320#if SIZEOF_WCHAR_T == 2
1321 /* in case the native representation is 2-bytes, we need to allocate a
1322 new normalized 4-byte version. */
1323 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001324 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1325 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 PyErr_NoMemory();
1327 return -1;
1328 }
1329 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1330 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001331 _PyUnicode_UTF8(unicode) = NULL;
1332 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001333 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1334 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001335 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 PyObject_FREE(_PyUnicode_WSTR(unicode));
1337 _PyUnicode_WSTR(unicode) = NULL;
1338 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1339#else
1340 assert(num_surrogates == 0);
1341
Victor Stinnerc3c74152011-10-02 20:39:55 +02001342 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001343 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001344 _PyUnicode_UTF8(unicode) = NULL;
1345 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1347#endif
1348 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1349 }
1350 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001351 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 return 0;
1353}
1354
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001355int
1356_PyUnicode_ReadyReplace(PyObject **op)
1357{
1358 return unicode_ready(op, 1);
1359}
1360
1361int
1362_PyUnicode_Ready(PyObject *op)
1363{
1364 return unicode_ready(&op, 0);
1365}
1366
Alexander Belopolsky40018472011-02-26 01:02:56 +00001367static void
1368unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001369{
Walter Dörwald16807132007-05-25 13:52:07 +00001370 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001371 case SSTATE_NOT_INTERNED:
1372 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001373
Benjamin Peterson29060642009-01-31 22:14:21 +00001374 case SSTATE_INTERNED_MORTAL:
1375 /* revive dead object temporarily for DelItem */
1376 Py_REFCNT(unicode) = 3;
1377 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1378 Py_FatalError(
1379 "deletion of interned string failed");
1380 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001381
Benjamin Peterson29060642009-01-31 22:14:21 +00001382 case SSTATE_INTERNED_IMMORTAL:
1383 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001384
Benjamin Peterson29060642009-01-31 22:14:21 +00001385 default:
1386 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001387 }
1388
Victor Stinner03490912011-10-03 23:45:12 +02001389 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001391 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001392 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393
1394 if (PyUnicode_IS_COMPACT(unicode)) {
1395 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001396 }
1397 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001398 if (_PyUnicode_DATA_ANY(unicode))
1399 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001400 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001401 }
1402}
1403
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001404#ifdef Py_DEBUG
1405static int
1406unicode_is_singleton(PyObject *unicode)
1407{
1408 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1409 if (unicode == unicode_empty)
1410 return 1;
1411 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1412 {
1413 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1414 if (ch < 256 && unicode_latin1[ch] == unicode)
1415 return 1;
1416 }
1417 return 0;
1418}
1419#endif
1420
Alexander Belopolsky40018472011-02-26 01:02:56 +00001421static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001422unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001423{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001424 if (Py_REFCNT(unicode) != 1)
1425 return 0;
1426 if (PyUnicode_CHECK_INTERNED(unicode))
1427 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001428#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001429 /* singleton refcount is greater than 1 */
1430 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001431#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001432 return 1;
1433}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001434
Victor Stinnerfe226c02011-10-03 03:52:20 +02001435static int
1436unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1437{
1438 PyObject *unicode;
1439 Py_ssize_t old_length;
1440
1441 assert(p_unicode != NULL);
1442 unicode = *p_unicode;
1443
1444 assert(unicode != NULL);
1445 assert(PyUnicode_Check(unicode));
1446 assert(0 <= length);
1447
Victor Stinner910337b2011-10-03 03:20:16 +02001448 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001449 old_length = PyUnicode_WSTR_LENGTH(unicode);
1450 else
1451 old_length = PyUnicode_GET_LENGTH(unicode);
1452 if (old_length == length)
1453 return 0;
1454
Victor Stinnerfe226c02011-10-03 03:52:20 +02001455 if (!unicode_resizable(unicode)) {
1456 PyObject *copy = resize_copy(unicode, length);
1457 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001458 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001459 Py_DECREF(*p_unicode);
1460 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001461 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001462 }
1463
Victor Stinnerfe226c02011-10-03 03:52:20 +02001464 if (PyUnicode_IS_COMPACT(unicode)) {
1465 *p_unicode = resize_compact(unicode, length);
1466 if (*p_unicode == NULL)
1467 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001468 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001469 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001470 }
1471 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001472}
1473
Alexander Belopolsky40018472011-02-26 01:02:56 +00001474int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001475PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001476{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001477 PyObject *unicode;
1478 if (p_unicode == NULL) {
1479 PyErr_BadInternalCall();
1480 return -1;
1481 }
1482 unicode = *p_unicode;
1483 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1484 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1485 {
1486 PyErr_BadInternalCall();
1487 return -1;
1488 }
1489 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001490}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001491
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492static PyObject*
1493get_latin1_char(unsigned char ch)
1494{
Victor Stinnera464fc12011-10-02 20:39:30 +02001495 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001497 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001498 if (!unicode)
1499 return NULL;
1500 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001501 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001502 unicode_latin1[ch] = unicode;
1503 }
1504 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001505 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001506}
1507
Alexander Belopolsky40018472011-02-26 01:02:56 +00001508PyObject *
1509PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001510{
1511 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 Py_UCS4 maxchar = 0;
1513 Py_ssize_t num_surrogates;
1514
1515 if (u == NULL)
1516 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001517
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001518 /* If the Unicode data is known at construction time, we can apply
1519 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521 /* Optimization for empty strings */
1522 if (size == 0 && unicode_empty != NULL) {
1523 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001524 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001525 }
Tim Petersced69f82003-09-16 20:30:58 +00001526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527 /* Single character Unicode objects in the Latin-1 range are
1528 shared when using this constructor */
1529 if (size == 1 && *u < 256)
1530 return get_latin1_char((unsigned char)*u);
1531
1532 /* If not empty and not single character, copy the Unicode data
1533 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001534 if (find_maxchar_surrogates(u, u + size,
1535 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001536 return NULL;
1537
1538 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1539 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001540 if (!unicode)
1541 return NULL;
1542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 switch (PyUnicode_KIND(unicode)) {
1544 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001545 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001546 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1547 break;
1548 case PyUnicode_2BYTE_KIND:
1549#if Py_UNICODE_SIZE == 2
1550 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1551#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001552 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1554#endif
1555 break;
1556 case PyUnicode_4BYTE_KIND:
1557#if SIZEOF_WCHAR_T == 2
1558 /* This is the only case which has to process surrogates, thus
1559 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001560 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561#else
1562 assert(num_surrogates == 0);
1563 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1564#endif
1565 break;
1566 default:
1567 assert(0 && "Impossible state");
1568 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001569
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001570 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571 return (PyObject *)unicode;
1572}
1573
Alexander Belopolsky40018472011-02-26 01:02:56 +00001574PyObject *
1575PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001576{
1577 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001578
Benjamin Peterson14339b62009-01-31 16:36:08 +00001579 if (size < 0) {
1580 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001581 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001582 return NULL;
1583 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001584
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001585 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001586 some optimizations which share commonly used objects.
1587 Also, this means the input must be UTF-8, so fall back to the
1588 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001589 if (u != NULL) {
1590
Benjamin Peterson29060642009-01-31 22:14:21 +00001591 /* Optimization for empty strings */
1592 if (size == 0 && unicode_empty != NULL) {
1593 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001594 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001595 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001596
1597 /* Single characters are shared when using this constructor.
1598 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 if (size == 1 && Py_CHARMASK(*u) < 128)
1600 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001601
1602 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001603 }
1604
Walter Dörwald55507312007-05-18 13:12:10 +00001605 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001606 if (!unicode)
1607 return NULL;
1608
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001609 return (PyObject *)unicode;
1610}
1611
Alexander Belopolsky40018472011-02-26 01:02:56 +00001612PyObject *
1613PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001614{
1615 size_t size = strlen(u);
1616 if (size > PY_SSIZE_T_MAX) {
1617 PyErr_SetString(PyExc_OverflowError, "input too long");
1618 return NULL;
1619 }
1620
1621 return PyUnicode_FromStringAndSize(u, size);
1622}
1623
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001624PyObject *
1625_PyUnicode_FromId(_Py_Identifier *id)
1626{
1627 if (!id->object) {
1628 id->object = PyUnicode_FromString(id->string);
1629 if (!id->object)
1630 return NULL;
1631 PyUnicode_InternInPlace(&id->object);
1632 assert(!id->next);
1633 id->next = static_strings;
1634 static_strings = id;
1635 }
1636 Py_INCREF(id->object);
1637 return id->object;
1638}
1639
1640void
1641_PyUnicode_ClearStaticStrings()
1642{
1643 _Py_Identifier *i;
1644 for (i = static_strings; i; i = i->next) {
1645 Py_DECREF(i->object);
1646 i->object = NULL;
1647 i->next = NULL;
1648 }
1649}
1650
Victor Stinnere57b1c02011-09-28 22:20:48 +02001651static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001652unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001653{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001654 PyObject *res;
1655#ifdef Py_DEBUG
1656 const unsigned char *p;
1657 const unsigned char *end = s + size;
1658 for (p=s; p < end; p++) {
1659 assert(*p < 128);
1660 }
1661#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001662 if (size == 1)
1663 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001664 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001665 if (!res)
1666 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001667 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001668 return res;
1669}
1670
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001671static Py_UCS4
1672kind_maxchar_limit(unsigned int kind)
1673{
1674 switch(kind) {
1675 case PyUnicode_1BYTE_KIND:
1676 return 0x80;
1677 case PyUnicode_2BYTE_KIND:
1678 return 0x100;
1679 case PyUnicode_4BYTE_KIND:
1680 return 0x10000;
1681 default:
1682 assert(0 && "invalid kind");
1683 return 0x10ffff;
1684 }
1685}
1686
Victor Stinner702c7342011-10-05 13:50:52 +02001687static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001688_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001689{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001691 unsigned char max_char = 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001693
1694 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001695 if (size == 1)
1696 return get_latin1_char(u[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 for (i = 0; i < size; i++) {
1698 if (u[i] & 0x80) {
Victor Stinnerb9275c12011-10-05 14:01:42 +02001699 max_char = 255;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 break;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001701 }
1702 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02001703 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704 if (!res)
1705 return NULL;
1706 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001707 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001708 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001709}
1710
Victor Stinnere57b1c02011-09-28 22:20:48 +02001711static PyObject*
1712_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001713{
1714 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001715 Py_UCS2 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001716 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001717
1718 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001719 if (size == 1 && u[0] < 256)
1720 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001721 for (i = 0; i < size; i++) {
1722 if (u[i] > max_char) {
1723 max_char = u[i];
1724 if (max_char >= 256)
1725 break;
1726 }
1727 }
1728 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729 if (!res)
1730 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001731 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001732 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
1733 else
1734 for (i = 0; i < size; i++)
1735 PyUnicode_1BYTE_DATA(res)[i] = (Py_UCS1)u[i];
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001736 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001737 return res;
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
1741_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742{
1743 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001744 Py_UCS4 max_char = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001745 Py_ssize_t i;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001746
1747 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001748 if (size == 1 && u[0] < 256)
1749 return get_latin1_char(u[0]);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001750 for (i = 0; i < size; i++) {
1751 if (u[i] > max_char) {
1752 max_char = u[i];
1753 if (max_char >= 0x10000)
1754 break;
1755 }
1756 }
1757 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!res)
1759 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001760 if (max_char < 256)
1761 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1762 PyUnicode_1BYTE_DATA(res));
1763 else if (max_char < 0x10000)
1764 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1765 PyUnicode_2BYTE_DATA(res));
1766 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001768 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 return res;
1770}
1771
1772PyObject*
1773PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1774{
1775 switch(kind) {
1776 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001779 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001781 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001782 default:
1783 assert(0 && "invalid kind");
1784 PyErr_SetString(PyExc_SystemError, "invalid kind");
1785 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001786 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787}
1788
Victor Stinner25a4b292011-10-06 12:31:55 +02001789/* Ensure that a string uses the most efficient storage, if it is not the
1790 case: create a new string with of the right kind. Write NULL into *p_unicode
1791 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001792static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001793unicode_adjust_maxchar(PyObject **p_unicode)
1794{
1795 PyObject *unicode, *copy;
1796 Py_UCS4 max_char;
1797 Py_ssize_t i, len;
1798 unsigned int kind;
1799
1800 assert(p_unicode != NULL);
1801 unicode = *p_unicode;
1802 assert(PyUnicode_IS_READY(unicode));
1803 if (PyUnicode_IS_ASCII(unicode))
1804 return;
1805
1806 len = PyUnicode_GET_LENGTH(unicode);
1807 kind = PyUnicode_KIND(unicode);
1808 if (kind == PyUnicode_1BYTE_KIND) {
1809 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
1810 for (i = 0; i < len; i++) {
1811 if (u[i] & 0x80)
1812 return;
1813 }
1814 max_char = 127;
1815 }
1816 else if (kind == PyUnicode_2BYTE_KIND) {
1817 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
1818 max_char = 0;
1819 for (i = 0; i < len; i++) {
1820 if (u[i] > max_char) {
1821 max_char = u[i];
1822 if (max_char >= 256)
1823 return;
1824 }
1825 }
1826 }
1827 else {
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001828 const Py_UCS4 *u;
Victor Stinner25a4b292011-10-06 12:31:55 +02001829 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitrou15a66cf2011-10-06 15:25:32 +02001830 u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001831 max_char = 0;
1832 for (i = 0; i < len; i++) {
1833 if (u[i] > max_char) {
1834 max_char = u[i];
1835 if (max_char >= 0x10000)
1836 return;
1837 }
1838 }
1839 }
Victor Stinner200f2132011-10-06 13:27:56 +02001840 assert(max_char < PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinner25a4b292011-10-06 12:31:55 +02001841 copy = PyUnicode_New(len, max_char);
1842 copy_characters(copy, 0, unicode, 0, len);
1843 Py_DECREF(unicode);
1844 *p_unicode = copy;
1845}
1846
Victor Stinner034f6cf2011-09-30 02:26:44 +02001847PyObject*
1848PyUnicode_Copy(PyObject *unicode)
1849{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001850 Py_ssize_t size;
1851 PyObject *copy;
1852 void *data;
1853
Victor Stinner034f6cf2011-09-30 02:26:44 +02001854 if (!PyUnicode_Check(unicode)) {
1855 PyErr_BadInternalCall();
1856 return NULL;
1857 }
1858 if (PyUnicode_READY(unicode))
1859 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001860
1861 size = PyUnicode_GET_LENGTH(unicode);
1862 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1863 if (!copy)
1864 return NULL;
1865 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1866
1867 data = PyUnicode_DATA(unicode);
1868 switch (PyUnicode_KIND(unicode))
1869 {
1870 case PyUnicode_1BYTE_KIND:
1871 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1872 break;
1873 case PyUnicode_2BYTE_KIND:
1874 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1875 break;
1876 case PyUnicode_4BYTE_KIND:
1877 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1878 break;
1879 default:
1880 assert(0);
1881 break;
1882 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001883 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001884 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001885}
1886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001887
Victor Stinnerbc603d12011-10-02 01:00:40 +02001888/* Widen Unicode objects to larger buffers. Don't write terminating null
1889 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001890
1891void*
1892_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1893{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001894 Py_ssize_t len;
1895 void *result;
1896 unsigned int skind;
1897
1898 if (PyUnicode_READY(s))
1899 return NULL;
1900
1901 len = PyUnicode_GET_LENGTH(s);
1902 skind = PyUnicode_KIND(s);
1903 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001904 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001905 return NULL;
1906 }
1907 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001908 case PyUnicode_2BYTE_KIND:
1909 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1910 if (!result)
1911 return PyErr_NoMemory();
1912 assert(skind == PyUnicode_1BYTE_KIND);
1913 _PyUnicode_CONVERT_BYTES(
1914 Py_UCS1, Py_UCS2,
1915 PyUnicode_1BYTE_DATA(s),
1916 PyUnicode_1BYTE_DATA(s) + len,
1917 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001918 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001919 case PyUnicode_4BYTE_KIND:
1920 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1921 if (!result)
1922 return PyErr_NoMemory();
1923 if (skind == PyUnicode_2BYTE_KIND) {
1924 _PyUnicode_CONVERT_BYTES(
1925 Py_UCS2, Py_UCS4,
1926 PyUnicode_2BYTE_DATA(s),
1927 PyUnicode_2BYTE_DATA(s) + len,
1928 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001929 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001930 else {
1931 assert(skind == PyUnicode_1BYTE_KIND);
1932 _PyUnicode_CONVERT_BYTES(
1933 Py_UCS1, Py_UCS4,
1934 PyUnicode_1BYTE_DATA(s),
1935 PyUnicode_1BYTE_DATA(s) + len,
1936 result);
1937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001938 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001939 default:
1940 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001941 }
Victor Stinner01698042011-10-04 00:04:26 +02001942 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 return NULL;
1944}
1945
1946static Py_UCS4*
1947as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1948 int copy_null)
1949{
1950 int kind;
1951 void *data;
1952 Py_ssize_t len, targetlen;
1953 if (PyUnicode_READY(string) == -1)
1954 return NULL;
1955 kind = PyUnicode_KIND(string);
1956 data = PyUnicode_DATA(string);
1957 len = PyUnicode_GET_LENGTH(string);
1958 targetlen = len;
1959 if (copy_null)
1960 targetlen++;
1961 if (!target) {
1962 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1963 PyErr_NoMemory();
1964 return NULL;
1965 }
1966 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1967 if (!target) {
1968 PyErr_NoMemory();
1969 return NULL;
1970 }
1971 }
1972 else {
1973 if (targetsize < targetlen) {
1974 PyErr_Format(PyExc_SystemError,
1975 "string is longer than the buffer");
1976 if (copy_null && 0 < targetsize)
1977 target[0] = 0;
1978 return NULL;
1979 }
1980 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02001981 if (kind == PyUnicode_1BYTE_KIND) {
1982 Py_UCS1 *start = (Py_UCS1 *) data;
1983 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02001985 else if (kind == PyUnicode_2BYTE_KIND) {
1986 Py_UCS2 *start = (Py_UCS2 *) data;
1987 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
1988 }
1989 else {
1990 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02001992 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993 if (copy_null)
1994 target[len] = 0;
1995 return target;
1996}
1997
1998Py_UCS4*
1999PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2000 int copy_null)
2001{
2002 if (target == NULL || targetsize < 1) {
2003 PyErr_BadInternalCall();
2004 return NULL;
2005 }
2006 return as_ucs4(string, target, targetsize, copy_null);
2007}
2008
2009Py_UCS4*
2010PyUnicode_AsUCS4Copy(PyObject *string)
2011{
2012 return as_ucs4(string, NULL, 0, 1);
2013}
2014
2015#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002016
Alexander Belopolsky40018472011-02-26 01:02:56 +00002017PyObject *
2018PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002019{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002020 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002021 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002023 PyErr_BadInternalCall();
2024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002025 }
2026
Martin v. Löwis790465f2008-04-05 20:41:37 +00002027 if (size == -1) {
2028 size = wcslen(w);
2029 }
2030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002031 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002032}
2033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002035
Walter Dörwald346737f2007-05-31 10:44:43 +00002036static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002037makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2038 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002039{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002040 *fmt++ = '%';
2041 if (width) {
2042 if (zeropad)
2043 *fmt++ = '0';
2044 fmt += sprintf(fmt, "%d", width);
2045 }
2046 if (precision)
2047 fmt += sprintf(fmt, ".%d", precision);
2048 if (longflag)
2049 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002050 else if (longlongflag) {
2051 /* longlongflag should only ever be nonzero on machines with
2052 HAVE_LONG_LONG defined */
2053#ifdef HAVE_LONG_LONG
2054 char *f = PY_FORMAT_LONG_LONG;
2055 while (*f)
2056 *fmt++ = *f++;
2057#else
2058 /* we shouldn't ever get here */
2059 assert(0);
2060 *fmt++ = 'l';
2061#endif
2062 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002063 else if (size_tflag) {
2064 char *f = PY_FORMAT_SIZE_T;
2065 while (*f)
2066 *fmt++ = *f++;
2067 }
2068 *fmt++ = c;
2069 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002070}
2071
Victor Stinner96865452011-03-01 23:44:09 +00002072/* helper for PyUnicode_FromFormatV() */
2073
2074static const char*
2075parse_format_flags(const char *f,
2076 int *p_width, int *p_precision,
2077 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2078{
2079 int width, precision, longflag, longlongflag, size_tflag;
2080
2081 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2082 f++;
2083 width = 0;
2084 while (Py_ISDIGIT((unsigned)*f))
2085 width = (width*10) + *f++ - '0';
2086 precision = 0;
2087 if (*f == '.') {
2088 f++;
2089 while (Py_ISDIGIT((unsigned)*f))
2090 precision = (precision*10) + *f++ - '0';
2091 if (*f == '%') {
2092 /* "%.3%s" => f points to "3" */
2093 f--;
2094 }
2095 }
2096 if (*f == '\0') {
2097 /* bogus format "%.1" => go backward, f points to "1" */
2098 f--;
2099 }
2100 if (p_width != NULL)
2101 *p_width = width;
2102 if (p_precision != NULL)
2103 *p_precision = precision;
2104
2105 /* Handle %ld, %lu, %lld and %llu. */
2106 longflag = 0;
2107 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002108 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002109
2110 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002111 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002112 longflag = 1;
2113 ++f;
2114 }
2115#ifdef HAVE_LONG_LONG
2116 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002117 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002118 longlongflag = 1;
2119 f += 2;
2120 }
2121#endif
2122 }
2123 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002124 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002125 size_tflag = 1;
2126 ++f;
2127 }
2128 if (p_longflag != NULL)
2129 *p_longflag = longflag;
2130 if (p_longlongflag != NULL)
2131 *p_longlongflag = longlongflag;
2132 if (p_size_tflag != NULL)
2133 *p_size_tflag = size_tflag;
2134 return f;
2135}
2136
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002137/* maximum number of characters required for output of %ld. 21 characters
2138 allows for 64-bit integers (in decimal) and an optional sign. */
2139#define MAX_LONG_CHARS 21
2140/* maximum number of characters required for output of %lld.
2141 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2142 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2143#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2144
Walter Dörwaldd2034312007-05-18 16:29:38 +00002145PyObject *
2146PyUnicode_FromFormatV(const char *format, va_list vargs)
2147{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002148 va_list count;
2149 Py_ssize_t callcount = 0;
2150 PyObject **callresults = NULL;
2151 PyObject **callresult = NULL;
2152 Py_ssize_t n = 0;
2153 int width = 0;
2154 int precision = 0;
2155 int zeropad;
2156 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002157 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002158 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002159 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002160 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2161 Py_UCS4 argmaxchar;
2162 Py_ssize_t numbersize = 0;
2163 char *numberresults = NULL;
2164 char *numberresult = NULL;
2165 Py_ssize_t i;
2166 int kind;
2167 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002168
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002169 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002170 /* step 1: count the number of %S/%R/%A/%s format specifications
2171 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2172 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002174 * also estimate a upper bound for all the number formats in the string,
2175 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002176 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002177 for (f = format; *f; f++) {
2178 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002179 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2181 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2182 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2183 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002186#ifdef HAVE_LONG_LONG
2187 if (longlongflag) {
2188 if (width < MAX_LONG_LONG_CHARS)
2189 width = MAX_LONG_LONG_CHARS;
2190 }
2191 else
2192#endif
2193 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2194 including sign. Decimal takes the most space. This
2195 isn't enough for octal. If a width is specified we
2196 need more (which we allocate later). */
2197 if (width < MAX_LONG_CHARS)
2198 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199
2200 /* account for the size + '\0' to separate numbers
2201 inside of the numberresults buffer */
2202 numbersize += (width + 1);
2203 }
2204 }
2205 else if ((unsigned char)*f > 127) {
2206 PyErr_Format(PyExc_ValueError,
2207 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2208 "string, got a non-ASCII byte: 0x%02x",
2209 (unsigned char)*f);
2210 return NULL;
2211 }
2212 }
2213 /* step 2: allocate memory for the results of
2214 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2215 if (callcount) {
2216 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2217 if (!callresults) {
2218 PyErr_NoMemory();
2219 return NULL;
2220 }
2221 callresult = callresults;
2222 }
2223 /* step 2.5: allocate memory for the results of formating numbers */
2224 if (numbersize) {
2225 numberresults = PyObject_Malloc(numbersize);
2226 if (!numberresults) {
2227 PyErr_NoMemory();
2228 goto fail;
2229 }
2230 numberresult = numberresults;
2231 }
2232
2233 /* step 3: format numbers and figure out how large a buffer we need */
2234 for (f = format; *f; f++) {
2235 if (*f == '%') {
2236 const char* p;
2237 int longflag;
2238 int longlongflag;
2239 int size_tflag;
2240 int numprinted;
2241
2242 p = f;
2243 zeropad = (f[1] == '0');
2244 f = parse_format_flags(f, &width, &precision,
2245 &longflag, &longlongflag, &size_tflag);
2246 switch (*f) {
2247 case 'c':
2248 {
2249 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002250 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 n++;
2252 break;
2253 }
2254 case '%':
2255 n++;
2256 break;
2257 case 'i':
2258 case 'd':
2259 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2260 width, precision, *f);
2261 if (longflag)
2262 numprinted = sprintf(numberresult, fmt,
2263 va_arg(count, long));
2264#ifdef HAVE_LONG_LONG
2265 else if (longlongflag)
2266 numprinted = sprintf(numberresult, fmt,
2267 va_arg(count, PY_LONG_LONG));
2268#endif
2269 else if (size_tflag)
2270 numprinted = sprintf(numberresult, fmt,
2271 va_arg(count, Py_ssize_t));
2272 else
2273 numprinted = sprintf(numberresult, fmt,
2274 va_arg(count, int));
2275 n += numprinted;
2276 /* advance by +1 to skip over the '\0' */
2277 numberresult += (numprinted + 1);
2278 assert(*(numberresult - 1) == '\0');
2279 assert(*(numberresult - 2) != '\0');
2280 assert(numprinted >= 0);
2281 assert(numberresult <= numberresults + numbersize);
2282 break;
2283 case 'u':
2284 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2285 width, precision, 'u');
2286 if (longflag)
2287 numprinted = sprintf(numberresult, fmt,
2288 va_arg(count, unsigned long));
2289#ifdef HAVE_LONG_LONG
2290 else if (longlongflag)
2291 numprinted = sprintf(numberresult, fmt,
2292 va_arg(count, unsigned PY_LONG_LONG));
2293#endif
2294 else if (size_tflag)
2295 numprinted = sprintf(numberresult, fmt,
2296 va_arg(count, size_t));
2297 else
2298 numprinted = sprintf(numberresult, fmt,
2299 va_arg(count, unsigned int));
2300 n += numprinted;
2301 numberresult += (numprinted + 1);
2302 assert(*(numberresult - 1) == '\0');
2303 assert(*(numberresult - 2) != '\0');
2304 assert(numprinted >= 0);
2305 assert(numberresult <= numberresults + numbersize);
2306 break;
2307 case 'x':
2308 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2309 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2310 n += numprinted;
2311 numberresult += (numprinted + 1);
2312 assert(*(numberresult - 1) == '\0');
2313 assert(*(numberresult - 2) != '\0');
2314 assert(numprinted >= 0);
2315 assert(numberresult <= numberresults + numbersize);
2316 break;
2317 case 'p':
2318 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2319 /* %p is ill-defined: ensure leading 0x. */
2320 if (numberresult[1] == 'X')
2321 numberresult[1] = 'x';
2322 else if (numberresult[1] != 'x') {
2323 memmove(numberresult + 2, numberresult,
2324 strlen(numberresult) + 1);
2325 numberresult[0] = '0';
2326 numberresult[1] = 'x';
2327 numprinted += 2;
2328 }
2329 n += numprinted;
2330 numberresult += (numprinted + 1);
2331 assert(*(numberresult - 1) == '\0');
2332 assert(*(numberresult - 2) != '\0');
2333 assert(numprinted >= 0);
2334 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002335 break;
2336 case 's':
2337 {
2338 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002339 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002340 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2341 if (!str)
2342 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343 /* since PyUnicode_DecodeUTF8 returns already flexible
2344 unicode objects, there is no need to call ready on them */
2345 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002346 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002347 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002348 /* Remember the str and switch to the next slot */
2349 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002350 break;
2351 }
2352 case 'U':
2353 {
2354 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002355 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 if (PyUnicode_READY(obj) == -1)
2357 goto fail;
2358 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002359 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002361 break;
2362 }
2363 case 'V':
2364 {
2365 PyObject *obj = va_arg(count, PyObject *);
2366 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002367 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002368 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002369 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002370 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 if (PyUnicode_READY(obj) == -1)
2372 goto fail;
2373 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002374 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002376 *callresult++ = NULL;
2377 }
2378 else {
2379 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2380 if (!str_obj)
2381 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002382 if (PyUnicode_READY(str_obj)) {
2383 Py_DECREF(str_obj);
2384 goto fail;
2385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002386 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002387 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002389 *callresult++ = str_obj;
2390 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 }
2393 case 'S':
2394 {
2395 PyObject *obj = va_arg(count, PyObject *);
2396 PyObject *str;
2397 assert(obj);
2398 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002400 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
2406 break;
2407 }
2408 case 'R':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
2411 PyObject *repr;
2412 assert(obj);
2413 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002414 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002415 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002417 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002419 /* Remember the repr and switch to the next slot */
2420 *callresult++ = repr;
2421 break;
2422 }
2423 case 'A':
2424 {
2425 PyObject *obj = va_arg(count, PyObject *);
2426 PyObject *ascii;
2427 assert(obj);
2428 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002429 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002430 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002432 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002434 /* Remember the repr and switch to the next slot */
2435 *callresult++ = ascii;
2436 break;
2437 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002438 default:
2439 /* if we stumble upon an unknown
2440 formatting code, copy the rest of
2441 the format string to the output
2442 string. (we cannot just skip the
2443 code, since there's no way to know
2444 what's in the argument list) */
2445 n += strlen(p);
2446 goto expand;
2447 }
2448 } else
2449 n++;
2450 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002451 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002452 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002454 we don't have to resize the string.
2455 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002456 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 if (!string)
2458 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 kind = PyUnicode_KIND(string);
2460 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002461 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002465 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002466 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002467
2468 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002469 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2470 /* checking for == because the last argument could be a empty
2471 string, which causes i to point to end, the assert at the end of
2472 the loop */
2473 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002474
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 switch (*f) {
2476 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002477 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 const int ordinal = va_arg(vargs, int);
2479 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002481 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002482 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002483 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002484 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002485 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 case 'p':
2487 /* unused, since we already have the result */
2488 if (*f == 'p')
2489 (void) va_arg(vargs, void *);
2490 else
2491 (void) va_arg(vargs, int);
2492 /* extract the result from numberresults and append. */
2493 for (; *numberresult; ++i, ++numberresult)
2494 PyUnicode_WRITE(kind, data, i, *numberresult);
2495 /* skip over the separating '\0' */
2496 assert(*numberresult == '\0');
2497 numberresult++;
2498 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 break;
2500 case 's':
2501 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002502 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002504 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 size = PyUnicode_GET_LENGTH(*callresult);
2506 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002507 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002508 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002509 /* We're done with the unicode()/repr() => forget it */
2510 Py_DECREF(*callresult);
2511 /* switch to next unicode()/repr() result */
2512 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 break;
2514 }
2515 case 'U':
2516 {
2517 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 Py_ssize_t size;
2519 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2520 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002521 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 break;
2524 }
2525 case 'V':
2526 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002528 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002529 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002531 size = PyUnicode_GET_LENGTH(obj);
2532 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002533 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002536 size = PyUnicode_GET_LENGTH(*callresult);
2537 assert(PyUnicode_KIND(*callresult) <=
2538 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002539 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002540 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002541 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002542 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002543 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 break;
2545 }
2546 case 'S':
2547 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002548 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002550 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002551 /* unused, since we already have the result */
2552 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002554 copy_characters(string, i, *callresult, 0, size);
2555 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002556 /* We're done with the unicode()/repr() => forget it */
2557 Py_DECREF(*callresult);
2558 /* switch to next unicode()/repr() result */
2559 ++callresult;
2560 break;
2561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002562 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002563 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002564 break;
2565 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 for (; *p; ++p, ++i)
2567 PyUnicode_WRITE(kind, data, i, *p);
2568 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 goto end;
2570 }
Victor Stinner1205f272010-09-11 00:54:47 +00002571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572 else {
2573 assert(i < PyUnicode_GET_LENGTH(string));
2574 PyUnicode_WRITE(kind, data, i++, *f);
2575 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002578
Benjamin Peterson29060642009-01-31 22:14:21 +00002579 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 if (callresults)
2581 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 if (numberresults)
2583 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002584 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002586 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002587 if (callresults) {
2588 PyObject **callresult2 = callresults;
2589 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002590 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 ++callresult2;
2592 }
2593 PyObject_Free(callresults);
2594 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 if (numberresults)
2596 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002597 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002598}
2599
Walter Dörwaldd2034312007-05-18 16:29:38 +00002600PyObject *
2601PyUnicode_FromFormat(const char *format, ...)
2602{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002603 PyObject* ret;
2604 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002605
2606#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002608#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002610#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002611 ret = PyUnicode_FromFormatV(format, vargs);
2612 va_end(vargs);
2613 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002614}
2615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616#ifdef HAVE_WCHAR_H
2617
Victor Stinner5593d8a2010-10-02 11:11:27 +00002618/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2619 convert a Unicode object to a wide character string.
2620
Victor Stinnerd88d9832011-09-06 02:00:05 +02002621 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002622 character) required to convert the unicode object. Ignore size argument.
2623
Victor Stinnerd88d9832011-09-06 02:00:05 +02002624 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002625 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002626 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002627static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002628unicode_aswidechar(PyUnicodeObject *unicode,
2629 wchar_t *w,
2630 Py_ssize_t size)
2631{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002632 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 const wchar_t *wstr;
2634
2635 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2636 if (wstr == NULL)
2637 return -1;
2638
Victor Stinner5593d8a2010-10-02 11:11:27 +00002639 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002640 if (size > res)
2641 size = res + 1;
2642 else
2643 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002644 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002645 return res;
2646 }
2647 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002649}
2650
2651Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002652PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002653 wchar_t *w,
2654 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002655{
2656 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002657 PyErr_BadInternalCall();
2658 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002659 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002660 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002661}
2662
Victor Stinner137c34c2010-09-29 10:25:54 +00002663wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002664PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002665 Py_ssize_t *size)
2666{
2667 wchar_t* buffer;
2668 Py_ssize_t buflen;
2669
2670 if (unicode == NULL) {
2671 PyErr_BadInternalCall();
2672 return NULL;
2673 }
2674
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002675 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 if (buflen == -1)
2677 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002679 PyErr_NoMemory();
2680 return NULL;
2681 }
2682
Victor Stinner137c34c2010-09-29 10:25:54 +00002683 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2684 if (buffer == NULL) {
2685 PyErr_NoMemory();
2686 return NULL;
2687 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002688 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 if (buflen == -1)
2690 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002691 if (size != NULL)
2692 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002693 return buffer;
2694}
2695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002697
Alexander Belopolsky40018472011-02-26 01:02:56 +00002698PyObject *
2699PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002702 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002703 PyErr_SetString(PyExc_ValueError,
2704 "chr() arg not in range(0x110000)");
2705 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002706 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002707
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002708 if (ordinal < 256)
2709 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002711 v = PyUnicode_New(1, ordinal);
2712 if (v == NULL)
2713 return NULL;
2714 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002715 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002716 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002717}
2718
Alexander Belopolsky40018472011-02-26 01:02:56 +00002719PyObject *
2720PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002722 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002723 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002724 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002725 if (PyUnicode_READY(obj))
2726 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002727 Py_INCREF(obj);
2728 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002729 }
2730 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002731 /* For a Unicode subtype that's not a Unicode object,
2732 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002733 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002734 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002735 PyErr_Format(PyExc_TypeError,
2736 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002737 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002738 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002739}
2740
Alexander Belopolsky40018472011-02-26 01:02:56 +00002741PyObject *
2742PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002743 const char *encoding,
2744 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002745{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002746 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002747 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002748
Guido van Rossumd57fd912000-03-10 22:53:23 +00002749 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002750 PyErr_BadInternalCall();
2751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002752 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002753
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002754 /* Decoding bytes objects is the most common case and should be fast */
2755 if (PyBytes_Check(obj)) {
2756 if (PyBytes_GET_SIZE(obj) == 0) {
2757 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002758 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002759 }
2760 else {
2761 v = PyUnicode_Decode(
2762 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2763 encoding, errors);
2764 }
2765 return v;
2766 }
2767
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002768 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002769 PyErr_SetString(PyExc_TypeError,
2770 "decoding str is not supported");
2771 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002772 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002773
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002774 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2775 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2776 PyErr_Format(PyExc_TypeError,
2777 "coercing to str: need bytes, bytearray "
2778 "or buffer-like object, %.80s found",
2779 Py_TYPE(obj)->tp_name);
2780 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002781 }
Tim Petersced69f82003-09-16 20:30:58 +00002782
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002783 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002784 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002785 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002786 }
Tim Petersced69f82003-09-16 20:30:58 +00002787 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002788 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002789
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002790 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002791 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002792}
2793
Victor Stinner600d3be2010-06-10 12:00:55 +00002794/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002795 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2796 1 on success. */
2797static int
2798normalize_encoding(const char *encoding,
2799 char *lower,
2800 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002801{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002802 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002803 char *l;
2804 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002805
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002806 e = encoding;
2807 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002808 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002809 while (*e) {
2810 if (l == l_end)
2811 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002812 if (Py_ISUPPER(*e)) {
2813 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002814 }
2815 else if (*e == '_') {
2816 *l++ = '-';
2817 e++;
2818 }
2819 else {
2820 *l++ = *e++;
2821 }
2822 }
2823 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002824 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002825}
2826
Alexander Belopolsky40018472011-02-26 01:02:56 +00002827PyObject *
2828PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002829 Py_ssize_t size,
2830 const char *encoding,
2831 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002832{
2833 PyObject *buffer = NULL, *unicode;
2834 Py_buffer info;
2835 char lower[11]; /* Enough for any encoding shortcut */
2836
2837 if (encoding == NULL)
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002838 return PyUnicode_DecodeUTF8(s, size, errors);
Fred Drakee4315f52000-05-09 19:53:39 +00002839
2840 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002841 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002842 if ((strcmp(lower, "utf-8") == 0) ||
2843 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002844 return PyUnicode_DecodeUTF8(s, size, errors);
2845 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002846 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002847 (strcmp(lower, "iso-8859-1") == 0))
2848 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002849#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002850 else if (strcmp(lower, "mbcs") == 0)
2851 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002852#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002853 else if (strcmp(lower, "ascii") == 0)
2854 return PyUnicode_DecodeASCII(s, size, errors);
2855 else if (strcmp(lower, "utf-16") == 0)
2856 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2857 else if (strcmp(lower, "utf-32") == 0)
2858 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2859 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002860
2861 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002862 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002863 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002864 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002865 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002866 if (buffer == NULL)
2867 goto onError;
2868 unicode = PyCodec_Decode(buffer, encoding, errors);
2869 if (unicode == NULL)
2870 goto onError;
2871 if (!PyUnicode_Check(unicode)) {
2872 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002873 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002874 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875 Py_DECREF(unicode);
2876 goto onError;
2877 }
2878 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002879#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002880 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002881 Py_DECREF(unicode);
2882 return NULL;
2883 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002884#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002885 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002887
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002889 Py_XDECREF(buffer);
2890 return NULL;
2891}
2892
Alexander Belopolsky40018472011-02-26 01:02:56 +00002893PyObject *
2894PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002895 const char *encoding,
2896 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002897{
2898 PyObject *v;
2899
2900 if (!PyUnicode_Check(unicode)) {
2901 PyErr_BadArgument();
2902 goto onError;
2903 }
2904
2905 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002907
2908 /* Decode via the codec registry */
2909 v = PyCodec_Decode(unicode, encoding, errors);
2910 if (v == NULL)
2911 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002912 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002913 return v;
2914
Benjamin Peterson29060642009-01-31 22:14:21 +00002915 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002916 return NULL;
2917}
2918
Alexander Belopolsky40018472011-02-26 01:02:56 +00002919PyObject *
2920PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002921 const char *encoding,
2922 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002923{
2924 PyObject *v;
2925
2926 if (!PyUnicode_Check(unicode)) {
2927 PyErr_BadArgument();
2928 goto onError;
2929 }
2930
2931 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002932 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002933
2934 /* Decode via the codec registry */
2935 v = PyCodec_Decode(unicode, encoding, errors);
2936 if (v == NULL)
2937 goto onError;
2938 if (!PyUnicode_Check(v)) {
2939 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002940 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002941 Py_TYPE(v)->tp_name);
2942 Py_DECREF(v);
2943 goto onError;
2944 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002945 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002946 return v;
2947
Benjamin Peterson29060642009-01-31 22:14:21 +00002948 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002949 return NULL;
2950}
2951
Alexander Belopolsky40018472011-02-26 01:02:56 +00002952PyObject *
2953PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002954 Py_ssize_t size,
2955 const char *encoding,
2956 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957{
2958 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002959
Guido van Rossumd57fd912000-03-10 22:53:23 +00002960 unicode = PyUnicode_FromUnicode(s, size);
2961 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002962 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002963 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2964 Py_DECREF(unicode);
2965 return v;
2966}
2967
Alexander Belopolsky40018472011-02-26 01:02:56 +00002968PyObject *
2969PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002970 const char *encoding,
2971 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002972{
2973 PyObject *v;
2974
2975 if (!PyUnicode_Check(unicode)) {
2976 PyErr_BadArgument();
2977 goto onError;
2978 }
2979
2980 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002981 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002982
2983 /* Encode via the codec registry */
2984 v = PyCodec_Encode(unicode, encoding, errors);
2985 if (v == NULL)
2986 goto onError;
2987 return v;
2988
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002990 return NULL;
2991}
2992
Victor Stinnerad158722010-10-27 00:25:46 +00002993PyObject *
2994PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00002995{
Victor Stinner99b95382011-07-04 14:23:54 +02002996#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00002997 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
2998 PyUnicode_GET_SIZE(unicode),
2999 NULL);
3000#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003001 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003002#else
Victor Stinner793b5312011-04-27 00:24:21 +02003003 PyInterpreterState *interp = PyThreadState_GET()->interp;
3004 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3005 cannot use it to encode and decode filenames before it is loaded. Load
3006 the Python codec requires to encode at least its own filename. Use the C
3007 version of the locale codec until the codec registry is initialized and
3008 the Python codec is loaded.
3009
3010 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3011 cannot only rely on it: check also interp->fscodec_initialized for
3012 subinterpreters. */
3013 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003014 return PyUnicode_AsEncodedString(unicode,
3015 Py_FileSystemDefaultEncoding,
3016 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003017 }
3018 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003019 /* locale encoding with surrogateescape */
3020 wchar_t *wchar;
3021 char *bytes;
3022 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003023 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003024
3025 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3026 if (wchar == NULL)
3027 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003028 bytes = _Py_wchar2char(wchar, &error_pos);
3029 if (bytes == NULL) {
3030 if (error_pos != (size_t)-1) {
3031 char *errmsg = strerror(errno);
3032 PyObject *exc = NULL;
3033 if (errmsg == NULL)
3034 errmsg = "Py_wchar2char() failed";
3035 raise_encode_exception(&exc,
3036 "filesystemencoding",
3037 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3038 error_pos, error_pos+1,
3039 errmsg);
3040 Py_XDECREF(exc);
3041 }
3042 else
3043 PyErr_NoMemory();
3044 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003045 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003046 }
3047 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003048
3049 bytes_obj = PyBytes_FromString(bytes);
3050 PyMem_Free(bytes);
3051 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003052 }
Victor Stinnerad158722010-10-27 00:25:46 +00003053#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003054}
3055
Alexander Belopolsky40018472011-02-26 01:02:56 +00003056PyObject *
3057PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003058 const char *encoding,
3059 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003060{
3061 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003062 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003063
Guido van Rossumd57fd912000-03-10 22:53:23 +00003064 if (!PyUnicode_Check(unicode)) {
3065 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003066 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003067 }
Fred Drakee4315f52000-05-09 19:53:39 +00003068
Victor Stinner2f283c22011-03-02 01:21:46 +00003069 if (encoding == NULL) {
3070 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003071 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003072 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner2f283c22011-03-02 01:21:46 +00003074 }
Fred Drakee4315f52000-05-09 19:53:39 +00003075
3076 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003077 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003078 if ((strcmp(lower, "utf-8") == 0) ||
3079 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003080 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003081 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003082 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003083 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003084 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003085 }
Victor Stinner37296e82010-06-10 13:36:23 +00003086 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003087 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003088 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003089 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003090#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003091 else if (strcmp(lower, "mbcs") == 0)
3092 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3093 PyUnicode_GET_SIZE(unicode),
3094 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003095#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003096 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003097 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003098 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003099
3100 /* Encode via the codec registry */
3101 v = PyCodec_Encode(unicode, encoding, errors);
3102 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003103 return NULL;
3104
3105 /* The normal path */
3106 if (PyBytes_Check(v))
3107 return v;
3108
3109 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003110 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003111 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003112 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003113
3114 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3115 "encoder %s returned bytearray instead of bytes",
3116 encoding);
3117 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003118 Py_DECREF(v);
3119 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003120 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003121
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3123 Py_DECREF(v);
3124 return b;
3125 }
3126
3127 PyErr_Format(PyExc_TypeError,
3128 "encoder did not return a bytes object (type=%.400s)",
3129 Py_TYPE(v)->tp_name);
3130 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003131 return NULL;
3132}
3133
Alexander Belopolsky40018472011-02-26 01:02:56 +00003134PyObject *
3135PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003136 const char *encoding,
3137 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003138{
3139 PyObject *v;
3140
3141 if (!PyUnicode_Check(unicode)) {
3142 PyErr_BadArgument();
3143 goto onError;
3144 }
3145
3146 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003147 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003148
3149 /* Encode via the codec registry */
3150 v = PyCodec_Encode(unicode, encoding, errors);
3151 if (v == NULL)
3152 goto onError;
3153 if (!PyUnicode_Check(v)) {
3154 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003155 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003156 Py_TYPE(v)->tp_name);
3157 Py_DECREF(v);
3158 goto onError;
3159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003160 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003161
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003163 return NULL;
3164}
3165
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003166PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003167PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003168 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003169 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3170}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003171
Christian Heimes5894ba72007-11-04 11:43:14 +00003172PyObject*
3173PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3174{
Victor Stinner99b95382011-07-04 14:23:54 +02003175#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003176 return PyUnicode_DecodeMBCS(s, size, NULL);
3177#elif defined(__APPLE__)
3178 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3179#else
Victor Stinner793b5312011-04-27 00:24:21 +02003180 PyInterpreterState *interp = PyThreadState_GET()->interp;
3181 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3182 cannot use it to encode and decode filenames before it is loaded. Load
3183 the Python codec requires to encode at least its own filename. Use the C
3184 version of the locale codec until the codec registry is initialized and
3185 the Python codec is loaded.
3186
3187 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3188 cannot only rely on it: check also interp->fscodec_initialized for
3189 subinterpreters. */
3190 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003191 return PyUnicode_Decode(s, size,
3192 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003193 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003194 }
3195 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003196 /* locale encoding with surrogateescape */
3197 wchar_t *wchar;
3198 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003199 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003200
3201 if (s[size] != '\0' || size != strlen(s)) {
3202 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3203 return NULL;
3204 }
3205
Victor Stinner168e1172010-10-16 23:16:16 +00003206 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003207 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003208 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003209
Victor Stinner168e1172010-10-16 23:16:16 +00003210 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003211 PyMem_Free(wchar);
3212 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003213 }
Victor Stinnerad158722010-10-27 00:25:46 +00003214#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003215}
3216
Martin v. Löwis011e8422009-05-05 04:43:17 +00003217
3218int
3219PyUnicode_FSConverter(PyObject* arg, void* addr)
3220{
3221 PyObject *output = NULL;
3222 Py_ssize_t size;
3223 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003224 if (arg == NULL) {
3225 Py_DECREF(*(PyObject**)addr);
3226 return 1;
3227 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003228 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003229 output = arg;
3230 Py_INCREF(output);
3231 }
3232 else {
3233 arg = PyUnicode_FromObject(arg);
3234 if (!arg)
3235 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003236 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003237 Py_DECREF(arg);
3238 if (!output)
3239 return 0;
3240 if (!PyBytes_Check(output)) {
3241 Py_DECREF(output);
3242 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3243 return 0;
3244 }
3245 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003246 size = PyBytes_GET_SIZE(output);
3247 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003248 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003249 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003250 Py_DECREF(output);
3251 return 0;
3252 }
3253 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003254 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003255}
3256
3257
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003258int
3259PyUnicode_FSDecoder(PyObject* arg, void* addr)
3260{
3261 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003262 if (arg == NULL) {
3263 Py_DECREF(*(PyObject**)addr);
3264 return 1;
3265 }
3266 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003267 if (PyUnicode_READY(arg))
3268 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003269 output = arg;
3270 Py_INCREF(output);
3271 }
3272 else {
3273 arg = PyBytes_FromObject(arg);
3274 if (!arg)
3275 return 0;
3276 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3277 PyBytes_GET_SIZE(arg));
3278 Py_DECREF(arg);
3279 if (!output)
3280 return 0;
3281 if (!PyUnicode_Check(output)) {
3282 Py_DECREF(output);
3283 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3284 return 0;
3285 }
3286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003287 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
3288 PyUnicode_GET_LENGTH(output), 0, 1)) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003289 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3290 Py_DECREF(output);
3291 return 0;
3292 }
3293 *(PyObject**)addr = output;
3294 return Py_CLEANUP_SUPPORTED;
3295}
3296
3297
Martin v. Löwis5b222132007-06-10 09:51:05 +00003298char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003299PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003300{
Christian Heimesf3863112007-11-22 07:46:41 +00003301 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3303
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003304 if (!PyUnicode_Check(unicode)) {
3305 PyErr_BadArgument();
3306 return NULL;
3307 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003308 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003309 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003311 if (PyUnicode_UTF8(unicode) == NULL) {
3312 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003313 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3314 if (bytes == NULL)
3315 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003316 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3317 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003318 Py_DECREF(bytes);
3319 return NULL;
3320 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003321 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3322 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003323 Py_DECREF(bytes);
3324 }
3325
3326 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003327 *psize = PyUnicode_UTF8_LENGTH(unicode);
3328 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003329}
3330
3331char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003332PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3335}
3336
3337#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003338static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003339#endif
3340
3341
3342Py_UNICODE *
3343PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3344{
3345 PyUnicodeObject *u;
3346 const unsigned char *one_byte;
3347#if SIZEOF_WCHAR_T == 4
3348 const Py_UCS2 *two_bytes;
3349#else
3350 const Py_UCS4 *four_bytes;
3351 const Py_UCS4 *ucs4_end;
3352 Py_ssize_t num_surrogates;
3353#endif
3354 wchar_t *w;
3355 wchar_t *wchar_end;
3356
3357 if (!PyUnicode_Check(unicode)) {
3358 PyErr_BadArgument();
3359 return NULL;
3360 }
3361 u = (PyUnicodeObject*)unicode;
3362 if (_PyUnicode_WSTR(u) == NULL) {
3363 /* Non-ASCII compact unicode object */
3364 assert(_PyUnicode_KIND(u) != 0);
3365 assert(PyUnicode_IS_READY(u));
3366
3367#ifdef Py_DEBUG
3368 ++unicode_as_unicode_calls;
3369#endif
3370
3371 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3372#if SIZEOF_WCHAR_T == 2
3373 four_bytes = PyUnicode_4BYTE_DATA(u);
3374 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3375 num_surrogates = 0;
3376
3377 for (; four_bytes < ucs4_end; ++four_bytes) {
3378 if (*four_bytes > 0xFFFF)
3379 ++num_surrogates;
3380 }
3381
3382 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3383 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3384 if (!_PyUnicode_WSTR(u)) {
3385 PyErr_NoMemory();
3386 return NULL;
3387 }
3388 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3389
3390 w = _PyUnicode_WSTR(u);
3391 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3392 four_bytes = PyUnicode_4BYTE_DATA(u);
3393 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3394 if (*four_bytes > 0xFFFF) {
3395 /* encode surrogate pair in this case */
3396 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3397 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3398 }
3399 else
3400 *w = *four_bytes;
3401
3402 if (w > wchar_end) {
3403 assert(0 && "Miscalculated string end");
3404 }
3405 }
3406 *w = 0;
3407#else
3408 /* sizeof(wchar_t) == 4 */
3409 Py_FatalError("Impossible unicode object state, wstr and str "
3410 "should share memory already.");
3411 return NULL;
3412#endif
3413 }
3414 else {
3415 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3416 (_PyUnicode_LENGTH(u) + 1));
3417 if (!_PyUnicode_WSTR(u)) {
3418 PyErr_NoMemory();
3419 return NULL;
3420 }
3421 if (!PyUnicode_IS_COMPACT_ASCII(u))
3422 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3423 w = _PyUnicode_WSTR(u);
3424 wchar_end = w + _PyUnicode_LENGTH(u);
3425
3426 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3427 one_byte = PyUnicode_1BYTE_DATA(u);
3428 for (; w < wchar_end; ++one_byte, ++w)
3429 *w = *one_byte;
3430 /* null-terminate the wstr */
3431 *w = 0;
3432 }
3433 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3434#if SIZEOF_WCHAR_T == 4
3435 two_bytes = PyUnicode_2BYTE_DATA(u);
3436 for (; w < wchar_end; ++two_bytes, ++w)
3437 *w = *two_bytes;
3438 /* null-terminate the wstr */
3439 *w = 0;
3440#else
3441 /* sizeof(wchar_t) == 2 */
3442 PyObject_FREE(_PyUnicode_WSTR(u));
3443 _PyUnicode_WSTR(u) = NULL;
3444 Py_FatalError("Impossible unicode object state, wstr "
3445 "and str should share memory already.");
3446 return NULL;
3447#endif
3448 }
3449 else {
3450 assert(0 && "This should never happen.");
3451 }
3452 }
3453 }
3454 if (size != NULL)
3455 *size = PyUnicode_WSTR_LENGTH(u);
3456 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003457}
3458
Alexander Belopolsky40018472011-02-26 01:02:56 +00003459Py_UNICODE *
3460PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003462 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003463}
3464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465
Alexander Belopolsky40018472011-02-26 01:02:56 +00003466Py_ssize_t
3467PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468{
3469 if (!PyUnicode_Check(unicode)) {
3470 PyErr_BadArgument();
3471 goto onError;
3472 }
3473 return PyUnicode_GET_SIZE(unicode);
3474
Benjamin Peterson29060642009-01-31 22:14:21 +00003475 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003476 return -1;
3477}
3478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003479Py_ssize_t
3480PyUnicode_GetLength(PyObject *unicode)
3481{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003482 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 PyErr_BadArgument();
3484 return -1;
3485 }
3486
3487 return PyUnicode_GET_LENGTH(unicode);
3488}
3489
3490Py_UCS4
3491PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3492{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003493 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3494 PyErr_BadArgument();
3495 return (Py_UCS4)-1;
3496 }
3497 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3498 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003499 return (Py_UCS4)-1;
3500 }
3501 return PyUnicode_READ_CHAR(unicode, index);
3502}
3503
3504int
3505PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3506{
3507 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003508 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003509 return -1;
3510 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003511 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3512 PyErr_SetString(PyExc_IndexError, "string index out of range");
3513 return -1;
3514 }
3515 if (_PyUnicode_Dirty(unicode))
3516 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3518 index, ch);
3519 return 0;
3520}
3521
Alexander Belopolsky40018472011-02-26 01:02:56 +00003522const char *
3523PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003524{
Victor Stinner42cb4622010-09-01 19:39:01 +00003525 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003526}
3527
Victor Stinner554f3f02010-06-16 23:33:54 +00003528/* create or adjust a UnicodeDecodeError */
3529static void
3530make_decode_exception(PyObject **exceptionObject,
3531 const char *encoding,
3532 const char *input, Py_ssize_t length,
3533 Py_ssize_t startpos, Py_ssize_t endpos,
3534 const char *reason)
3535{
3536 if (*exceptionObject == NULL) {
3537 *exceptionObject = PyUnicodeDecodeError_Create(
3538 encoding, input, length, startpos, endpos, reason);
3539 }
3540 else {
3541 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3542 goto onError;
3543 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3544 goto onError;
3545 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3546 goto onError;
3547 }
3548 return;
3549
3550onError:
3551 Py_DECREF(*exceptionObject);
3552 *exceptionObject = NULL;
3553}
3554
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003555/* error handling callback helper:
3556 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003557 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003558 and adjust various state variables.
3559 return 0 on success, -1 on error
3560*/
3561
Alexander Belopolsky40018472011-02-26 01:02:56 +00003562static int
3563unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003564 const char *encoding, const char *reason,
3565 const char **input, const char **inend, Py_ssize_t *startinpos,
3566 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3567 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003568{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003569 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003570
3571 PyObject *restuple = NULL;
3572 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003573 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003574 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003575 Py_ssize_t requiredsize;
3576 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003577 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003578 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003579 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003580 int res = -1;
3581
3582 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003583 *errorHandler = PyCodec_LookupError(errors);
3584 if (*errorHandler == NULL)
3585 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003586 }
3587
Victor Stinner554f3f02010-06-16 23:33:54 +00003588 make_decode_exception(exceptionObject,
3589 encoding,
3590 *input, *inend - *input,
3591 *startinpos, *endinpos,
3592 reason);
3593 if (*exceptionObject == NULL)
3594 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003595
3596 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3597 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003598 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003599 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003600 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 }
3603 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003604 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003605
3606 /* Copy back the bytes variables, which might have been modified by the
3607 callback */
3608 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3609 if (!inputobj)
3610 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003611 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003612 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003613 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003614 *input = PyBytes_AS_STRING(inputobj);
3615 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003616 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003617 /* we can DECREF safely, as the exception has another reference,
3618 so the object won't go away. */
3619 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003620
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003622 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003623 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003624 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3625 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003626 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003627
3628 /* need more space? (at least enough for what we
3629 have+the replacement+the rest of the string (starting
3630 at the new input position), so we won't have to check space
3631 when there are no errors in the rest of the string) */
3632 repptr = PyUnicode_AS_UNICODE(repunicode);
3633 repsize = PyUnicode_GET_SIZE(repunicode);
3634 requiredsize = *outpos + repsize + insize-newpos;
3635 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003636 if (requiredsize<2*outsize)
3637 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003638 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003639 goto onError;
3640 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003641 }
3642 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003643 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003644 Py_UNICODE_COPY(*outptr, repptr, repsize);
3645 *outptr += repsize;
3646 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003647
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648 /* we made it! */
3649 res = 0;
3650
Benjamin Peterson29060642009-01-31 22:14:21 +00003651 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003652 Py_XDECREF(restuple);
3653 return res;
3654}
3655
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003656/* --- UTF-7 Codec -------------------------------------------------------- */
3657
Antoine Pitrou244651a2009-05-04 18:56:13 +00003658/* See RFC2152 for details. We encode conservatively and decode liberally. */
3659
3660/* Three simple macros defining base-64. */
3661
3662/* Is c a base-64 character? */
3663
3664#define IS_BASE64(c) \
3665 (((c) >= 'A' && (c) <= 'Z') || \
3666 ((c) >= 'a' && (c) <= 'z') || \
3667 ((c) >= '0' && (c) <= '9') || \
3668 (c) == '+' || (c) == '/')
3669
3670/* given that c is a base-64 character, what is its base-64 value? */
3671
3672#define FROM_BASE64(c) \
3673 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3674 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3675 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3676 (c) == '+' ? 62 : 63)
3677
3678/* What is the base-64 character of the bottom 6 bits of n? */
3679
3680#define TO_BASE64(n) \
3681 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3682
3683/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3684 * decoded as itself. We are permissive on decoding; the only ASCII
3685 * byte not decoding to itself is the + which begins a base64
3686 * string. */
3687
3688#define DECODE_DIRECT(c) \
3689 ((c) <= 127 && (c) != '+')
3690
3691/* The UTF-7 encoder treats ASCII characters differently according to
3692 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3693 * the above). See RFC2152. This array identifies these different
3694 * sets:
3695 * 0 : "Set D"
3696 * alphanumeric and '(),-./:?
3697 * 1 : "Set O"
3698 * !"#$%&*;<=>@[]^_`{|}
3699 * 2 : "whitespace"
3700 * ht nl cr sp
3701 * 3 : special (must be base64 encoded)
3702 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3703 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003704
Tim Petersced69f82003-09-16 20:30:58 +00003705static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003706char utf7_category[128] = {
3707/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3708 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3709/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3710 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3711/* sp ! " # $ % & ' ( ) * + , - . / */
3712 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3713/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3714 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3715/* @ A B C D E F G H I J K L M N O */
3716 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3717/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3718 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3719/* ` a b c d e f g h i j k l m n o */
3720 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3721/* p q r s t u v w x y z { | } ~ del */
3722 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003723};
3724
Antoine Pitrou244651a2009-05-04 18:56:13 +00003725/* ENCODE_DIRECT: this character should be encoded as itself. The
3726 * answer depends on whether we are encoding set O as itself, and also
3727 * on whether we are encoding whitespace as itself. RFC2152 makes it
3728 * clear that the answers to these questions vary between
3729 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003730
Antoine Pitrou244651a2009-05-04 18:56:13 +00003731#define ENCODE_DIRECT(c, directO, directWS) \
3732 ((c) < 128 && (c) > 0 && \
3733 ((utf7_category[(c)] == 0) || \
3734 (directWS && (utf7_category[(c)] == 2)) || \
3735 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003736
Alexander Belopolsky40018472011-02-26 01:02:56 +00003737PyObject *
3738PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003739 Py_ssize_t size,
3740 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003741{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003742 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3743}
3744
Antoine Pitrou244651a2009-05-04 18:56:13 +00003745/* The decoder. The only state we preserve is our read position,
3746 * i.e. how many characters we have consumed. So if we end in the
3747 * middle of a shift sequence we have to back off the read position
3748 * and the output to the beginning of the sequence, otherwise we lose
3749 * all the shift state (seen bits, number of bits seen, high
3750 * surrogate). */
3751
Alexander Belopolsky40018472011-02-26 01:02:56 +00003752PyObject *
3753PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003754 Py_ssize_t size,
3755 const char *errors,
3756 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003757{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003758 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003759 Py_ssize_t startinpos;
3760 Py_ssize_t endinpos;
3761 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003762 const char *e;
3763 PyUnicodeObject *unicode;
3764 Py_UNICODE *p;
3765 const char *errmsg = "";
3766 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003767 Py_UNICODE *shiftOutStart;
3768 unsigned int base64bits = 0;
3769 unsigned long base64buffer = 0;
3770 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003771 PyObject *errorHandler = NULL;
3772 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003773
3774 unicode = _PyUnicode_New(size);
3775 if (!unicode)
3776 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003777 if (size == 0) {
3778 if (consumed)
3779 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003780 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003781 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003785 e = s + size;
3786
3787 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003788 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003789 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003790 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003791
Antoine Pitrou244651a2009-05-04 18:56:13 +00003792 if (inShift) { /* in a base-64 section */
3793 if (IS_BASE64(ch)) { /* consume a base-64 character */
3794 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3795 base64bits += 6;
3796 s++;
3797 if (base64bits >= 16) {
3798 /* we have enough bits for a UTF-16 value */
3799 Py_UNICODE outCh = (Py_UNICODE)
3800 (base64buffer >> (base64bits-16));
3801 base64bits -= 16;
3802 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3803 if (surrogate) {
3804 /* expecting a second surrogate */
3805 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3806#ifdef Py_UNICODE_WIDE
3807 *p++ = (((surrogate & 0x3FF)<<10)
3808 | (outCh & 0x3FF)) + 0x10000;
3809#else
3810 *p++ = surrogate;
3811 *p++ = outCh;
3812#endif
3813 surrogate = 0;
3814 }
3815 else {
3816 surrogate = 0;
3817 errmsg = "second surrogate missing";
3818 goto utf7Error;
3819 }
3820 }
3821 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3822 /* first surrogate */
3823 surrogate = outCh;
3824 }
3825 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3826 errmsg = "unexpected second surrogate";
3827 goto utf7Error;
3828 }
3829 else {
3830 *p++ = outCh;
3831 }
3832 }
3833 }
3834 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003835 inShift = 0;
3836 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003837 if (surrogate) {
3838 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003839 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003840 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003841 if (base64bits > 0) { /* left-over bits */
3842 if (base64bits >= 6) {
3843 /* We've seen at least one base-64 character */
3844 errmsg = "partial character in shift sequence";
3845 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003846 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003847 else {
3848 /* Some bits remain; they should be zero */
3849 if (base64buffer != 0) {
3850 errmsg = "non-zero padding bits in shift sequence";
3851 goto utf7Error;
3852 }
3853 }
3854 }
3855 if (ch != '-') {
3856 /* '-' is absorbed; other terminating
3857 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003858 *p++ = ch;
3859 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860 }
3861 }
3862 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003863 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003864 s++; /* consume '+' */
3865 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003866 s++;
3867 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003868 }
3869 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003870 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003871 shiftOutStart = p;
3872 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873 }
3874 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003875 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003876 *p++ = ch;
3877 s++;
3878 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003879 else {
3880 startinpos = s-starts;
3881 s++;
3882 errmsg = "unexpected special character";
3883 goto utf7Error;
3884 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003887 outpos = p-PyUnicode_AS_UNICODE(unicode);
3888 endinpos = s-starts;
3889 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003890 errors, &errorHandler,
3891 "utf7", errmsg,
3892 &starts, &e, &startinpos, &endinpos, &exc, &s,
3893 &unicode, &outpos, &p))
3894 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895 }
3896
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 /* end of string */
3898
3899 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3900 /* if we're in an inconsistent state, that's an error */
3901 if (surrogate ||
3902 (base64bits >= 6) ||
3903 (base64bits > 0 && base64buffer != 0)) {
3904 outpos = p-PyUnicode_AS_UNICODE(unicode);
3905 endinpos = size;
3906 if (unicode_decode_call_errorhandler(
3907 errors, &errorHandler,
3908 "utf7", "unterminated shift sequence",
3909 &starts, &e, &startinpos, &endinpos, &exc, &s,
3910 &unicode, &outpos, &p))
3911 goto onError;
3912 if (s < e)
3913 goto restart;
3914 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003915 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003916
3917 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003918 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 if (inShift) {
3920 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003921 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003922 }
3923 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003924 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003925 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003926 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003927
Victor Stinnerfe226c02011-10-03 03:52:20 +02003928 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003929 goto onError;
3930
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003931 Py_XDECREF(errorHandler);
3932 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003933#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003934 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 Py_DECREF(unicode);
3936 return NULL;
3937 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003938#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003939 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 return (PyObject *)unicode;
3941
Benjamin Peterson29060642009-01-31 22:14:21 +00003942 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003943 Py_XDECREF(errorHandler);
3944 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003945 Py_DECREF(unicode);
3946 return NULL;
3947}
3948
3949
Alexander Belopolsky40018472011-02-26 01:02:56 +00003950PyObject *
3951PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003952 Py_ssize_t size,
3953 int base64SetO,
3954 int base64WhiteSpace,
3955 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003957 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003958 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003959 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003961 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003962 unsigned int base64bits = 0;
3963 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003964 char * out;
3965 char * start;
3966
3967 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003969
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003970 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003971 return PyErr_NoMemory();
3972
Antoine Pitrou244651a2009-05-04 18:56:13 +00003973 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003974 if (v == NULL)
3975 return NULL;
3976
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003977 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978 for (;i < size; ++i) {
3979 Py_UNICODE ch = s[i];
3980
Antoine Pitrou244651a2009-05-04 18:56:13 +00003981 if (inShift) {
3982 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3983 /* shifting out */
3984 if (base64bits) { /* output remaining bits */
3985 *out++ = TO_BASE64(base64buffer << (6-base64bits));
3986 base64buffer = 0;
3987 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003988 }
3989 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003990 /* Characters not in the BASE64 set implicitly unshift the sequence
3991 so no '-' is required, except if the character is itself a '-' */
3992 if (IS_BASE64(ch) || ch == '-') {
3993 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003994 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 *out++ = (char) ch;
3996 }
3997 else {
3998 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00003999 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004001 else { /* not in a shift sequence */
4002 if (ch == '+') {
4003 *out++ = '+';
4004 *out++ = '-';
4005 }
4006 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4007 *out++ = (char) ch;
4008 }
4009 else {
4010 *out++ = '+';
4011 inShift = 1;
4012 goto encode_char;
4013 }
4014 }
4015 continue;
4016encode_char:
4017#ifdef Py_UNICODE_WIDE
4018 if (ch >= 0x10000) {
4019 /* code first surrogate */
4020 base64bits += 16;
4021 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4022 while (base64bits >= 6) {
4023 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4024 base64bits -= 6;
4025 }
4026 /* prepare second surrogate */
4027 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4028 }
4029#endif
4030 base64bits += 16;
4031 base64buffer = (base64buffer << 16) | ch;
4032 while (base64bits >= 6) {
4033 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4034 base64bits -= 6;
4035 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004036 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004037 if (base64bits)
4038 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4039 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004040 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004041 if (_PyBytes_Resize(&v, out - start) < 0)
4042 return NULL;
4043 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004044}
4045
Antoine Pitrou244651a2009-05-04 18:56:13 +00004046#undef IS_BASE64
4047#undef FROM_BASE64
4048#undef TO_BASE64
4049#undef DECODE_DIRECT
4050#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004051
Guido van Rossumd57fd912000-03-10 22:53:23 +00004052/* --- UTF-8 Codec -------------------------------------------------------- */
4053
Tim Petersced69f82003-09-16 20:30:58 +00004054static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004055char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004056 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4057 illegal prefix. See RFC 3629 for details */
4058 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4059 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004060 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004061 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4062 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4063 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4064 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004065 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4066 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 +00004067 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4068 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004069 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4070 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4071 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4072 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4073 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 +00004074};
4075
Alexander Belopolsky40018472011-02-26 01:02:56 +00004076PyObject *
4077PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004078 Py_ssize_t size,
4079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004080{
Walter Dörwald69652032004-09-07 20:24:22 +00004081 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4082}
4083
Antoine Pitrouab868312009-01-10 15:40:25 +00004084/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4085#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4086
4087/* Mask to quickly check whether a C 'long' contains a
4088 non-ASCII, UTF8-encoded char. */
4089#if (SIZEOF_LONG == 8)
4090# define ASCII_CHAR_MASK 0x8080808080808080L
4091#elif (SIZEOF_LONG == 4)
4092# define ASCII_CHAR_MASK 0x80808080L
4093#else
4094# error C 'long' size should be either 4 or 8!
4095#endif
4096
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004097/* Scans a UTF-8 string and returns the maximum character to be expected,
4098 the size of the decoded unicode string and if any major errors were
4099 encountered.
4100
4101 This function does check basic UTF-8 sanity, it does however NOT CHECK
4102 if the string contains surrogates, and if all continuation bytes are
4103 within the correct ranges, these checks are performed in
4104 PyUnicode_DecodeUTF8Stateful.
4105
4106 If it sets has_errors to 1, it means the value of unicode_size and max_char
4107 will be bogus and you should not rely on useful information in them.
4108 */
4109static Py_UCS4
4110utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4111 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4112 int *has_errors)
4113{
4114 Py_ssize_t n;
4115 Py_ssize_t char_count = 0;
4116 Py_UCS4 max_char = 127, new_max;
4117 Py_UCS4 upper_bound;
4118 const unsigned char *p = (const unsigned char *)s;
4119 const unsigned char *end = p + string_size;
4120 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4121 int err = 0;
4122
4123 for (; p < end && !err; ++p, ++char_count) {
4124 /* Only check value if it's not a ASCII char... */
4125 if (*p < 0x80) {
4126 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4127 an explanation. */
4128 if (!((size_t) p & LONG_PTR_MASK)) {
4129 /* Help register allocation */
4130 register const unsigned char *_p = p;
4131 while (_p < aligned_end) {
4132 unsigned long value = *(unsigned long *) _p;
4133 if (value & ASCII_CHAR_MASK)
4134 break;
4135 _p += SIZEOF_LONG;
4136 char_count += SIZEOF_LONG;
4137 }
4138 p = _p;
4139 if (p == end)
4140 break;
4141 }
4142 }
4143 if (*p >= 0x80) {
4144 n = utf8_code_length[*p];
4145 new_max = max_char;
4146 switch (n) {
4147 /* invalid start byte */
4148 case 0:
4149 err = 1;
4150 break;
4151 case 2:
4152 /* Code points between 0x00FF and 0x07FF inclusive.
4153 Approximate the upper bound of the code point,
4154 if this flips over 255 we can be sure it will be more
4155 than 255 and the string will need 2 bytes per code coint,
4156 if it stays under or equal to 255, we can be sure 1 byte
4157 is enough.
4158 ((*p & 0b00011111) << 6) | 0b00111111 */
4159 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4160 if (max_char < upper_bound)
4161 new_max = upper_bound;
4162 /* Ensure we track at least that we left ASCII space. */
4163 if (new_max < 128)
4164 new_max = 128;
4165 break;
4166 case 3:
4167 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4168 always > 255 and <= 65535 and will always need 2 bytes. */
4169 if (max_char < 65535)
4170 new_max = 65535;
4171 break;
4172 case 4:
4173 /* Code point will be above 0xFFFF for sure in this case. */
4174 new_max = 65537;
4175 break;
4176 /* Internal error, this should be caught by the first if */
4177 case 1:
4178 default:
4179 assert(0 && "Impossible case in utf8_max_char_and_size");
4180 err = 1;
4181 }
4182 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004183 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004184 --n;
4185 /* Check if the follow up chars are all valid continuation bytes */
4186 if (n >= 1) {
4187 const unsigned char *cont;
4188 if ((p + n) >= end) {
4189 if (consumed == 0)
4190 /* incomplete data, non-incremental decoding */
4191 err = 1;
4192 break;
4193 }
4194 for (cont = p + 1; cont < (p + n); ++cont) {
4195 if ((*cont & 0xc0) != 0x80) {
4196 err = 1;
4197 break;
4198 }
4199 }
4200 p += n;
4201 }
4202 else
4203 err = 1;
4204 max_char = new_max;
4205 }
4206 }
4207
4208 if (unicode_size)
4209 *unicode_size = char_count;
4210 if (has_errors)
4211 *has_errors = err;
4212 return max_char;
4213}
4214
4215/* Similar to PyUnicode_WRITE but can also write into wstr field
4216 of the legacy unicode representation */
4217#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4218 do { \
4219 const int k_ = (kind); \
4220 if (k_ == PyUnicode_WCHAR_KIND) \
4221 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4222 else if (k_ == PyUnicode_1BYTE_KIND) \
4223 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4224 else if (k_ == PyUnicode_2BYTE_KIND) \
4225 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4226 else \
4227 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4228 } while (0)
4229
Alexander Belopolsky40018472011-02-26 01:02:56 +00004230PyObject *
4231PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004232 Py_ssize_t size,
4233 const char *errors,
4234 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004235{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004236 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004237 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004238 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004239 Py_ssize_t startinpos;
4240 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004241 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004242 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004243 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004244 PyObject *errorHandler = NULL;
4245 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004246 Py_UCS4 maxchar = 0;
4247 Py_ssize_t unicode_size;
4248 Py_ssize_t i;
4249 int kind;
4250 void *data;
4251 int has_errors;
4252 Py_UNICODE *error_outptr;
4253#if SIZEOF_WCHAR_T == 2
4254 Py_ssize_t wchar_offset = 0;
4255#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004256
Walter Dörwald69652032004-09-07 20:24:22 +00004257 if (size == 0) {
4258 if (consumed)
4259 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004260 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004262 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4263 consumed, &has_errors);
4264 if (has_errors) {
4265 unicode = _PyUnicode_New(size);
4266 if (!unicode)
4267 return NULL;
4268 kind = PyUnicode_WCHAR_KIND;
4269 data = PyUnicode_AS_UNICODE(unicode);
4270 assert(data != NULL);
4271 }
4272 else {
4273 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4274 if (!unicode)
4275 return NULL;
4276 /* When the string is ASCII only, just use memcpy and return.
4277 unicode_size may be != size if there is an incomplete UTF-8
4278 sequence at the end of the ASCII block. */
4279 if (maxchar < 128 && size == unicode_size) {
4280 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4281 return (PyObject *)unicode;
4282 }
4283 kind = PyUnicode_KIND(unicode);
4284 data = PyUnicode_DATA(unicode);
4285 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004286 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004288 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004289 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004290
4291 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004292 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004293
4294 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004295 /* Fast path for runs of ASCII characters. Given that common UTF-8
4296 input will consist of an overwhelming majority of ASCII
4297 characters, we try to optimize for this case by checking
4298 as many characters as a C 'long' can contain.
4299 First, check if we can do an aligned read, as most CPUs have
4300 a penalty for unaligned reads.
4301 */
4302 if (!((size_t) s & LONG_PTR_MASK)) {
4303 /* Help register allocation */
4304 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004305 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004306 while (_s < aligned_end) {
4307 /* Read a whole long at a time (either 4 or 8 bytes),
4308 and do a fast unrolled copy if it only contains ASCII
4309 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004310 unsigned long value = *(unsigned long *) _s;
4311 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004312 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004313 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4314 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4315 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4316 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004317#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004318 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4319 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4320 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4321 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004322#endif
4323 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004324 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004325 }
4326 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004327 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004328 if (s == e)
4329 break;
4330 ch = (unsigned char)*s;
4331 }
4332 }
4333
4334 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004336 s++;
4337 continue;
4338 }
4339
4340 n = utf8_code_length[ch];
4341
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004342 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 if (consumed)
4344 break;
4345 else {
4346 errmsg = "unexpected end of data";
4347 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004348 endinpos = startinpos+1;
4349 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4350 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004351 goto utf8Error;
4352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004353 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004354
4355 switch (n) {
4356
4357 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004358 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004359 startinpos = s-starts;
4360 endinpos = startinpos+1;
4361 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004362
4363 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004364 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004365 startinpos = s-starts;
4366 endinpos = startinpos+1;
4367 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004368
4369 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004370 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004371 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004373 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004374 goto utf8Error;
4375 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004377 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379 break;
4380
4381 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004382 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4383 will result in surrogates in range d800-dfff. Surrogates are
4384 not valid UTF-8 so they are rejected.
4385 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4386 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004387 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004388 (s[2] & 0xc0) != 0x80 ||
4389 ((unsigned char)s[0] == 0xE0 &&
4390 (unsigned char)s[1] < 0xA0) ||
4391 ((unsigned char)s[0] == 0xED &&
4392 (unsigned char)s[1] > 0x9F)) {
4393 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004395 endinpos = startinpos + 1;
4396
4397 /* if s[1] first two bits are 1 and 0, then the invalid
4398 continuation byte is s[2], so increment endinpos by 1,
4399 if not, s[1] is invalid and endinpos doesn't need to
4400 be incremented. */
4401 if ((s[1] & 0xC0) == 0x80)
4402 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004403 goto utf8Error;
4404 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004405 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004406 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004407 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004408 break;
4409
4410 case 4:
4411 if ((s[1] & 0xc0) != 0x80 ||
4412 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004413 (s[3] & 0xc0) != 0x80 ||
4414 ((unsigned char)s[0] == 0xF0 &&
4415 (unsigned char)s[1] < 0x90) ||
4416 ((unsigned char)s[0] == 0xF4 &&
4417 (unsigned char)s[1] > 0x8F)) {
4418 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004420 endinpos = startinpos + 1;
4421 if ((s[1] & 0xC0) == 0x80) {
4422 endinpos++;
4423 if ((s[2] & 0xC0) == 0x80)
4424 endinpos++;
4425 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004426 goto utf8Error;
4427 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004428 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004429 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4430 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004432 /* If the string is flexible or we have native UCS-4, write
4433 directly.. */
4434 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4435 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004437 else {
4438 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004440 /* translate from 10000..10FFFF to 0..FFFF */
4441 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004443 /* high surrogate = top 10 bits added to D800 */
4444 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4445 (Py_UNICODE)(0xD800 + (ch >> 10)));
4446
4447 /* low surrogate = bottom 10 bits added to DC00 */
4448 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4449 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4450 }
4451#if SIZEOF_WCHAR_T == 2
4452 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004453#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004454 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004455 }
4456 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004457 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004458
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004460 /* If this is not yet a resizable string, make it one.. */
4461 if (kind != PyUnicode_WCHAR_KIND) {
4462 const Py_UNICODE *u;
4463 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4464 if (!new_unicode)
4465 goto onError;
4466 u = PyUnicode_AsUnicode((PyObject *)unicode);
4467 if (!u)
4468 goto onError;
4469#if SIZEOF_WCHAR_T == 2
4470 i += wchar_offset;
4471#endif
4472 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4473 Py_DECREF(unicode);
4474 unicode = new_unicode;
4475 kind = 0;
4476 data = PyUnicode_AS_UNICODE(new_unicode);
4477 assert(data != NULL);
4478 }
4479 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 if (unicode_decode_call_errorhandler(
4481 errors, &errorHandler,
4482 "utf8", errmsg,
4483 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004484 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004486 /* Update data because unicode_decode_call_errorhandler might have
4487 re-created or resized the unicode object. */
4488 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004489 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004491 /* Ensure the unicode_size calculation above was correct: */
4492 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4493
Walter Dörwald69652032004-09-07 20:24:22 +00004494 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004497 /* Adjust length and ready string when it contained errors and
4498 is of the old resizable kind. */
4499 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004500 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004501 goto onError;
4502 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004503
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004504 Py_XDECREF(errorHandler);
4505 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004506#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004507 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 Py_DECREF(unicode);
4509 return NULL;
4510 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004511#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004512 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004513 return (PyObject *)unicode;
4514
Benjamin Peterson29060642009-01-31 22:14:21 +00004515 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004516 Py_XDECREF(errorHandler);
4517 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518 Py_DECREF(unicode);
4519 return NULL;
4520}
4521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004522#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004523
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004524#ifdef __APPLE__
4525
4526/* Simplified UTF-8 decoder using surrogateescape error handler,
4527 used to decode the command line arguments on Mac OS X. */
4528
4529wchar_t*
4530_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4531{
4532 int n;
4533 const char *e;
4534 wchar_t *unicode, *p;
4535
4536 /* Note: size will always be longer than the resulting Unicode
4537 character count */
4538 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4539 PyErr_NoMemory();
4540 return NULL;
4541 }
4542 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4543 if (!unicode)
4544 return NULL;
4545
4546 /* Unpack UTF-8 encoded data */
4547 p = unicode;
4548 e = s + size;
4549 while (s < e) {
4550 Py_UCS4 ch = (unsigned char)*s;
4551
4552 if (ch < 0x80) {
4553 *p++ = (wchar_t)ch;
4554 s++;
4555 continue;
4556 }
4557
4558 n = utf8_code_length[ch];
4559 if (s + n > e) {
4560 goto surrogateescape;
4561 }
4562
4563 switch (n) {
4564 case 0:
4565 case 1:
4566 goto surrogateescape;
4567
4568 case 2:
4569 if ((s[1] & 0xc0) != 0x80)
4570 goto surrogateescape;
4571 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4572 assert ((ch > 0x007F) && (ch <= 0x07FF));
4573 *p++ = (wchar_t)ch;
4574 break;
4575
4576 case 3:
4577 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4578 will result in surrogates in range d800-dfff. Surrogates are
4579 not valid UTF-8 so they are rejected.
4580 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4581 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4582 if ((s[1] & 0xc0) != 0x80 ||
4583 (s[2] & 0xc0) != 0x80 ||
4584 ((unsigned char)s[0] == 0xE0 &&
4585 (unsigned char)s[1] < 0xA0) ||
4586 ((unsigned char)s[0] == 0xED &&
4587 (unsigned char)s[1] > 0x9F)) {
4588
4589 goto surrogateescape;
4590 }
4591 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4592 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004594 break;
4595
4596 case 4:
4597 if ((s[1] & 0xc0) != 0x80 ||
4598 (s[2] & 0xc0) != 0x80 ||
4599 (s[3] & 0xc0) != 0x80 ||
4600 ((unsigned char)s[0] == 0xF0 &&
4601 (unsigned char)s[1] < 0x90) ||
4602 ((unsigned char)s[0] == 0xF4 &&
4603 (unsigned char)s[1] > 0x8F)) {
4604 goto surrogateescape;
4605 }
4606 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4607 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4608 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4609
4610#if SIZEOF_WCHAR_T == 4
4611 *p++ = (wchar_t)ch;
4612#else
4613 /* compute and append the two surrogates: */
4614
4615 /* translate from 10000..10FFFF to 0..FFFF */
4616 ch -= 0x10000;
4617
4618 /* high surrogate = top 10 bits added to D800 */
4619 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4620
4621 /* low surrogate = bottom 10 bits added to DC00 */
4622 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4623#endif
4624 break;
4625 }
4626 s += n;
4627 continue;
4628
4629 surrogateescape:
4630 *p++ = 0xDC00 + ch;
4631 s++;
4632 }
4633 *p = L'\0';
4634 return unicode;
4635}
4636
4637#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004639/* Primary internal function which creates utf8 encoded bytes objects.
4640
4641 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004642 and allocate exactly as much space needed at the end. Else allocate the
4643 maximum possible needed (4 result bytes per Unicode character), and return
4644 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004645*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004646PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004647_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004648{
Tim Peters602f7402002-04-27 18:03:26 +00004649#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004650
Guido van Rossum98297ee2007-11-06 21:34:58 +00004651 Py_ssize_t i; /* index into s of next input byte */
4652 PyObject *result; /* result string object */
4653 char *p; /* next free byte in output buffer */
4654 Py_ssize_t nallocated; /* number of result bytes allocated */
4655 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004656 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004657 PyObject *errorHandler = NULL;
4658 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004659 int kind;
4660 void *data;
4661 Py_ssize_t size;
4662 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4663#if SIZEOF_WCHAR_T == 2
4664 Py_ssize_t wchar_offset = 0;
4665#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004667 if (!PyUnicode_Check(unicode)) {
4668 PyErr_BadArgument();
4669 return NULL;
4670 }
4671
4672 if (PyUnicode_READY(unicode) == -1)
4673 return NULL;
4674
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004675 if (PyUnicode_UTF8(unicode))
4676 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4677 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004678
4679 kind = PyUnicode_KIND(unicode);
4680 data = PyUnicode_DATA(unicode);
4681 size = PyUnicode_GET_LENGTH(unicode);
4682
Tim Peters602f7402002-04-27 18:03:26 +00004683 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004684
Tim Peters602f7402002-04-27 18:03:26 +00004685 if (size <= MAX_SHORT_UNICHARS) {
4686 /* Write into the stack buffer; nallocated can't overflow.
4687 * At the end, we'll allocate exactly as much heap space as it
4688 * turns out we need.
4689 */
4690 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004691 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004692 p = stackbuf;
4693 }
4694 else {
4695 /* Overallocate on the heap, and give the excess back at the end. */
4696 nallocated = size * 4;
4697 if (nallocated / 4 != size) /* overflow! */
4698 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004699 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004700 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004701 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004702 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004703 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004704
Tim Peters602f7402002-04-27 18:03:26 +00004705 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004706 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004707
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004708 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004709 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004710 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004711
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004713 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004714 *p++ = (char)(0xc0 | (ch >> 6));
4715 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004716 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 Py_ssize_t newpos;
4718 PyObject *rep;
4719 Py_ssize_t repsize, k, startpos;
4720 startpos = i-1;
4721#if SIZEOF_WCHAR_T == 2
4722 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004723#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004724 rep = unicode_encode_call_errorhandler(
4725 errors, &errorHandler, "utf-8", "surrogates not allowed",
4726 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4727 &exc, startpos, startpos+1, &newpos);
4728 if (!rep)
4729 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004731 if (PyBytes_Check(rep))
4732 repsize = PyBytes_GET_SIZE(rep);
4733 else
4734 repsize = PyUnicode_GET_SIZE(rep);
4735
4736 if (repsize > 4) {
4737 Py_ssize_t offset;
4738
4739 if (result == NULL)
4740 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004741 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004742 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004744 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4745 /* integer overflow */
4746 PyErr_NoMemory();
4747 goto error;
4748 }
4749 nallocated += repsize - 4;
4750 if (result != NULL) {
4751 if (_PyBytes_Resize(&result, nallocated) < 0)
4752 goto error;
4753 } else {
4754 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004755 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004756 goto error;
4757 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4758 }
4759 p = PyBytes_AS_STRING(result) + offset;
4760 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004762 if (PyBytes_Check(rep)) {
4763 char *prep = PyBytes_AS_STRING(rep);
4764 for(k = repsize; k > 0; k--)
4765 *p++ = *prep++;
4766 } else /* rep is unicode */ {
4767 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4768 Py_UNICODE c;
4769
4770 for(k=0; k<repsize; k++) {
4771 c = prep[k];
4772 if (0x80 <= c) {
4773 raise_encode_exception(&exc, "utf-8",
4774 PyUnicode_AS_UNICODE(unicode),
4775 size, i-1, i,
4776 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004777 goto error;
4778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004780 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004781 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004782 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004783 } else if (ch < 0x10000) {
4784 *p++ = (char)(0xe0 | (ch >> 12));
4785 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4786 *p++ = (char)(0x80 | (ch & 0x3f));
4787 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004788 /* Encode UCS4 Unicode ordinals */
4789 *p++ = (char)(0xf0 | (ch >> 18));
4790 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4791 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4792 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004793#if SIZEOF_WCHAR_T == 2
4794 wchar_offset++;
4795#endif
Tim Peters602f7402002-04-27 18:03:26 +00004796 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004797 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004798
Guido van Rossum98297ee2007-11-06 21:34:58 +00004799 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004800 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004801 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004802 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004803 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004804 }
4805 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004806 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004807 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004808 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004809 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004812 Py_XDECREF(errorHandler);
4813 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004814 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004815 error:
4816 Py_XDECREF(errorHandler);
4817 Py_XDECREF(exc);
4818 Py_XDECREF(result);
4819 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004820
Tim Peters602f7402002-04-27 18:03:26 +00004821#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004822}
4823
Alexander Belopolsky40018472011-02-26 01:02:56 +00004824PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004825PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4826 Py_ssize_t size,
4827 const char *errors)
4828{
4829 PyObject *v, *unicode;
4830
4831 unicode = PyUnicode_FromUnicode(s, size);
4832 if (unicode == NULL)
4833 return NULL;
4834 v = _PyUnicode_AsUTF8String(unicode, errors);
4835 Py_DECREF(unicode);
4836 return v;
4837}
4838
4839PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004840PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004842 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004843}
4844
Walter Dörwald41980ca2007-08-16 21:55:45 +00004845/* --- UTF-32 Codec ------------------------------------------------------- */
4846
4847PyObject *
4848PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 Py_ssize_t size,
4850 const char *errors,
4851 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004852{
4853 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4854}
4855
4856PyObject *
4857PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 Py_ssize_t size,
4859 const char *errors,
4860 int *byteorder,
4861 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004862{
4863 const char *starts = s;
4864 Py_ssize_t startinpos;
4865 Py_ssize_t endinpos;
4866 Py_ssize_t outpos;
4867 PyUnicodeObject *unicode;
4868 Py_UNICODE *p;
4869#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004870 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004871 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004872#else
4873 const int pairs = 0;
4874#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004875 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004876 int bo = 0; /* assume native ordering by default */
4877 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004878 /* Offsets from q for retrieving bytes in the right order. */
4879#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4880 int iorder[] = {0, 1, 2, 3};
4881#else
4882 int iorder[] = {3, 2, 1, 0};
4883#endif
4884 PyObject *errorHandler = NULL;
4885 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004886
Walter Dörwald41980ca2007-08-16 21:55:45 +00004887 q = (unsigned char *)s;
4888 e = q + size;
4889
4890 if (byteorder)
4891 bo = *byteorder;
4892
4893 /* Check for BOM marks (U+FEFF) in the input and adjust current
4894 byte order setting accordingly. In native mode, the leading BOM
4895 mark is skipped, in all other modes, it is copied to the output
4896 stream as-is (giving a ZWNBSP character). */
4897 if (bo == 0) {
4898 if (size >= 4) {
4899 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004901#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004902 if (bom == 0x0000FEFF) {
4903 q += 4;
4904 bo = -1;
4905 }
4906 else if (bom == 0xFFFE0000) {
4907 q += 4;
4908 bo = 1;
4909 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004910#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004911 if (bom == 0x0000FEFF) {
4912 q += 4;
4913 bo = 1;
4914 }
4915 else if (bom == 0xFFFE0000) {
4916 q += 4;
4917 bo = -1;
4918 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004919#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004920 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004921 }
4922
4923 if (bo == -1) {
4924 /* force LE */
4925 iorder[0] = 0;
4926 iorder[1] = 1;
4927 iorder[2] = 2;
4928 iorder[3] = 3;
4929 }
4930 else if (bo == 1) {
4931 /* force BE */
4932 iorder[0] = 3;
4933 iorder[1] = 2;
4934 iorder[2] = 1;
4935 iorder[3] = 0;
4936 }
4937
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004938 /* On narrow builds we split characters outside the BMP into two
4939 codepoints => count how much extra space we need. */
4940#ifndef Py_UNICODE_WIDE
4941 for (qq = q; qq < e; qq += 4)
4942 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4943 pairs++;
4944#endif
4945
4946 /* This might be one to much, because of a BOM */
4947 unicode = _PyUnicode_New((size+3)/4+pairs);
4948 if (!unicode)
4949 return NULL;
4950 if (size == 0)
4951 return (PyObject *)unicode;
4952
4953 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004954 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004955
Walter Dörwald41980ca2007-08-16 21:55:45 +00004956 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004957 Py_UCS4 ch;
4958 /* remaining bytes at the end? (size should be divisible by 4) */
4959 if (e-q<4) {
4960 if (consumed)
4961 break;
4962 errmsg = "truncated data";
4963 startinpos = ((const char *)q)-starts;
4964 endinpos = ((const char *)e)-starts;
4965 goto utf32Error;
4966 /* The remaining input chars are ignored if the callback
4967 chooses to skip the input */
4968 }
4969 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4970 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 if (ch >= 0x110000)
4973 {
4974 errmsg = "codepoint not in range(0x110000)";
4975 startinpos = ((const char *)q)-starts;
4976 endinpos = startinpos+4;
4977 goto utf32Error;
4978 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004979#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004980 if (ch >= 0x10000)
4981 {
4982 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4983 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4984 }
4985 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 *p++ = ch;
4988 q += 4;
4989 continue;
4990 utf32Error:
4991 outpos = p-PyUnicode_AS_UNICODE(unicode);
4992 if (unicode_decode_call_errorhandler(
4993 errors, &errorHandler,
4994 "utf32", errmsg,
4995 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
4996 &unicode, &outpos, &p))
4997 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998 }
4999
5000 if (byteorder)
5001 *byteorder = bo;
5002
5003 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005004 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005005
5006 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005007 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008 goto onError;
5009
5010 Py_XDECREF(errorHandler);
5011 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005012#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005013 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005014 Py_DECREF(unicode);
5015 return NULL;
5016 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005017#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005018 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 return (PyObject *)unicode;
5020
Benjamin Peterson29060642009-01-31 22:14:21 +00005021 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005022 Py_DECREF(unicode);
5023 Py_XDECREF(errorHandler);
5024 Py_XDECREF(exc);
5025 return NULL;
5026}
5027
5028PyObject *
5029PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005030 Py_ssize_t size,
5031 const char *errors,
5032 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005033{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005034 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005036 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005037#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005038 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039#else
5040 const int pairs = 0;
5041#endif
5042 /* Offsets from p for storing byte pairs in the right order. */
5043#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5044 int iorder[] = {0, 1, 2, 3};
5045#else
5046 int iorder[] = {3, 2, 1, 0};
5047#endif
5048
Benjamin Peterson29060642009-01-31 22:14:21 +00005049#define STORECHAR(CH) \
5050 do { \
5051 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5052 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5053 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5054 p[iorder[0]] = (CH) & 0xff; \
5055 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 } while(0)
5057
5058 /* In narrow builds we can output surrogate pairs as one codepoint,
5059 so we need less space. */
5060#ifndef Py_UNICODE_WIDE
5061 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5063 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5064 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005066 nsize = (size - pairs + (byteorder == 0));
5067 bytesize = nsize * 4;
5068 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005069 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005070 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 if (v == NULL)
5072 return NULL;
5073
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005074 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005076 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005078 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005079
5080 if (byteorder == -1) {
5081 /* force LE */
5082 iorder[0] = 0;
5083 iorder[1] = 1;
5084 iorder[2] = 2;
5085 iorder[3] = 3;
5086 }
5087 else if (byteorder == 1) {
5088 /* force BE */
5089 iorder[0] = 3;
5090 iorder[1] = 2;
5091 iorder[2] = 1;
5092 iorder[3] = 0;
5093 }
5094
5095 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005096 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5099 Py_UCS4 ch2 = *s;
5100 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5101 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5102 s++;
5103 size--;
5104 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005105 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106#endif
5107 STORECHAR(ch);
5108 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005109
5110 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005111 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112#undef STORECHAR
5113}
5114
Alexander Belopolsky40018472011-02-26 01:02:56 +00005115PyObject *
5116PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005117{
5118 if (!PyUnicode_Check(unicode)) {
5119 PyErr_BadArgument();
5120 return NULL;
5121 }
5122 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005123 PyUnicode_GET_SIZE(unicode),
5124 NULL,
5125 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005126}
5127
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128/* --- UTF-16 Codec ------------------------------------------------------- */
5129
Tim Peters772747b2001-08-09 22:21:55 +00005130PyObject *
5131PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005132 Py_ssize_t size,
5133 const char *errors,
5134 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005135{
Walter Dörwald69652032004-09-07 20:24:22 +00005136 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5137}
5138
Antoine Pitrouab868312009-01-10 15:40:25 +00005139/* Two masks for fast checking of whether a C 'long' may contain
5140 UTF16-encoded surrogate characters. This is an efficient heuristic,
5141 assuming that non-surrogate characters with a code point >= 0x8000 are
5142 rare in most input.
5143 FAST_CHAR_MASK is used when the input is in native byte ordering,
5144 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005145*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005146#if (SIZEOF_LONG == 8)
5147# define FAST_CHAR_MASK 0x8000800080008000L
5148# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5149#elif (SIZEOF_LONG == 4)
5150# define FAST_CHAR_MASK 0x80008000L
5151# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5152#else
5153# error C 'long' size should be either 4 or 8!
5154#endif
5155
Walter Dörwald69652032004-09-07 20:24:22 +00005156PyObject *
5157PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 Py_ssize_t size,
5159 const char *errors,
5160 int *byteorder,
5161 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005162{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005163 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005164 Py_ssize_t startinpos;
5165 Py_ssize_t endinpos;
5166 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005167 PyUnicodeObject *unicode;
5168 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005169 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005170 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005171 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005172 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005173 /* Offsets from q for retrieving byte pairs in the right order. */
5174#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5175 int ihi = 1, ilo = 0;
5176#else
5177 int ihi = 0, ilo = 1;
5178#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005179 PyObject *errorHandler = NULL;
5180 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005181
5182 /* Note: size will always be longer than the resulting Unicode
5183 character count */
5184 unicode = _PyUnicode_New(size);
5185 if (!unicode)
5186 return NULL;
5187 if (size == 0)
5188 return (PyObject *)unicode;
5189
5190 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005191 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005192 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005193 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005194
5195 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005196 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005198 /* Check for BOM marks (U+FEFF) in the input and adjust current
5199 byte order setting accordingly. In native mode, the leading BOM
5200 mark is skipped, in all other modes, it is copied to the output
5201 stream as-is (giving a ZWNBSP character). */
5202 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005203 if (size >= 2) {
5204 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005205#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005206 if (bom == 0xFEFF) {
5207 q += 2;
5208 bo = -1;
5209 }
5210 else if (bom == 0xFFFE) {
5211 q += 2;
5212 bo = 1;
5213 }
Tim Petersced69f82003-09-16 20:30:58 +00005214#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005215 if (bom == 0xFEFF) {
5216 q += 2;
5217 bo = 1;
5218 }
5219 else if (bom == 0xFFFE) {
5220 q += 2;
5221 bo = -1;
5222 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005223#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005225 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005226
Tim Peters772747b2001-08-09 22:21:55 +00005227 if (bo == -1) {
5228 /* force LE */
5229 ihi = 1;
5230 ilo = 0;
5231 }
5232 else if (bo == 1) {
5233 /* force BE */
5234 ihi = 0;
5235 ilo = 1;
5236 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005237#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5238 native_ordering = ilo < ihi;
5239#else
5240 native_ordering = ilo > ihi;
5241#endif
Tim Peters772747b2001-08-09 22:21:55 +00005242
Antoine Pitrouab868312009-01-10 15:40:25 +00005243 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005244 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005246 /* First check for possible aligned read of a C 'long'. Unaligned
5247 reads are more expensive, better to defer to another iteration. */
5248 if (!((size_t) q & LONG_PTR_MASK)) {
5249 /* Fast path for runs of non-surrogate chars. */
5250 register const unsigned char *_q = q;
5251 Py_UNICODE *_p = p;
5252 if (native_ordering) {
5253 /* Native ordering is simple: as long as the input cannot
5254 possibly contain a surrogate char, do an unrolled copy
5255 of several 16-bit code points to the target object.
5256 The non-surrogate check is done on several input bytes
5257 at a time (as many as a C 'long' can contain). */
5258 while (_q < aligned_end) {
5259 unsigned long data = * (unsigned long *) _q;
5260 if (data & FAST_CHAR_MASK)
5261 break;
5262 _p[0] = ((unsigned short *) _q)[0];
5263 _p[1] = ((unsigned short *) _q)[1];
5264#if (SIZEOF_LONG == 8)
5265 _p[2] = ((unsigned short *) _q)[2];
5266 _p[3] = ((unsigned short *) _q)[3];
5267#endif
5268 _q += SIZEOF_LONG;
5269 _p += SIZEOF_LONG / 2;
5270 }
5271 }
5272 else {
5273 /* Byteswapped ordering is similar, but we must decompose
5274 the copy bytewise, and take care of zero'ing out the
5275 upper bytes if the target object is in 32-bit units
5276 (that is, in UCS-4 builds). */
5277 while (_q < aligned_end) {
5278 unsigned long data = * (unsigned long *) _q;
5279 if (data & SWAPPED_FAST_CHAR_MASK)
5280 break;
5281 /* Zero upper bytes in UCS-4 builds */
5282#if (Py_UNICODE_SIZE > 2)
5283 _p[0] = 0;
5284 _p[1] = 0;
5285#if (SIZEOF_LONG == 8)
5286 _p[2] = 0;
5287 _p[3] = 0;
5288#endif
5289#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005290 /* Issue #4916; UCS-4 builds on big endian machines must
5291 fill the two last bytes of each 4-byte unit. */
5292#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5293# define OFF 2
5294#else
5295# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005296#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005297 ((unsigned char *) _p)[OFF + 1] = _q[0];
5298 ((unsigned char *) _p)[OFF + 0] = _q[1];
5299 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5300 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5301#if (SIZEOF_LONG == 8)
5302 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5303 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5304 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5305 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5306#endif
5307#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005308 _q += SIZEOF_LONG;
5309 _p += SIZEOF_LONG / 2;
5310 }
5311 }
5312 p = _p;
5313 q = _q;
5314 if (q >= e)
5315 break;
5316 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005317 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005318
Benjamin Peterson14339b62009-01-31 16:36:08 +00005319 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005320
5321 if (ch < 0xD800 || ch > 0xDFFF) {
5322 *p++ = ch;
5323 continue;
5324 }
5325
5326 /* UTF-16 code pair: */
5327 if (q > e) {
5328 errmsg = "unexpected end of data";
5329 startinpos = (((const char *)q) - 2) - starts;
5330 endinpos = ((const char *)e) + 1 - starts;
5331 goto utf16Error;
5332 }
5333 if (0xD800 <= ch && ch <= 0xDBFF) {
5334 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5335 q += 2;
5336 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005337#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 *p++ = ch;
5339 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005340#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005341 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005342#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 continue;
5344 }
5345 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005346 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005347 startinpos = (((const char *)q)-4)-starts;
5348 endinpos = startinpos+2;
5349 goto utf16Error;
5350 }
5351
Benjamin Peterson14339b62009-01-31 16:36:08 +00005352 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 errmsg = "illegal encoding";
5354 startinpos = (((const char *)q)-2)-starts;
5355 endinpos = startinpos+2;
5356 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005357
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 utf16Error:
5359 outpos = p - PyUnicode_AS_UNICODE(unicode);
5360 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005361 errors,
5362 &errorHandler,
5363 "utf16", errmsg,
5364 &starts,
5365 (const char **)&e,
5366 &startinpos,
5367 &endinpos,
5368 &exc,
5369 (const char **)&q,
5370 &unicode,
5371 &outpos,
5372 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005375 /* remaining byte at the end? (size should be even) */
5376 if (e == q) {
5377 if (!consumed) {
5378 errmsg = "truncated data";
5379 startinpos = ((const char *)q) - starts;
5380 endinpos = ((const char *)e) + 1 - starts;
5381 outpos = p - PyUnicode_AS_UNICODE(unicode);
5382 if (unicode_decode_call_errorhandler(
5383 errors,
5384 &errorHandler,
5385 "utf16", errmsg,
5386 &starts,
5387 (const char **)&e,
5388 &startinpos,
5389 &endinpos,
5390 &exc,
5391 (const char **)&q,
5392 &unicode,
5393 &outpos,
5394 &p))
5395 goto onError;
5396 /* The remaining input chars are ignored if the callback
5397 chooses to skip the input */
5398 }
5399 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005400
5401 if (byteorder)
5402 *byteorder = bo;
5403
Walter Dörwald69652032004-09-07 20:24:22 +00005404 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005406
Guido van Rossumd57fd912000-03-10 22:53:23 +00005407 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005408 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409 goto onError;
5410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 Py_XDECREF(errorHandler);
5412 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005413#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005414 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005415 Py_DECREF(unicode);
5416 return NULL;
5417 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005418#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005419 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420 return (PyObject *)unicode;
5421
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005424 Py_XDECREF(errorHandler);
5425 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426 return NULL;
5427}
5428
Antoine Pitrouab868312009-01-10 15:40:25 +00005429#undef FAST_CHAR_MASK
5430#undef SWAPPED_FAST_CHAR_MASK
5431
Tim Peters772747b2001-08-09 22:21:55 +00005432PyObject *
5433PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005434 Py_ssize_t size,
5435 const char *errors,
5436 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005438 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005439 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005440 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005441#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005442 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005443#else
5444 const int pairs = 0;
5445#endif
Tim Peters772747b2001-08-09 22:21:55 +00005446 /* Offsets from p for storing byte pairs in the right order. */
5447#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5448 int ihi = 1, ilo = 0;
5449#else
5450 int ihi = 0, ilo = 1;
5451#endif
5452
Benjamin Peterson29060642009-01-31 22:14:21 +00005453#define STORECHAR(CH) \
5454 do { \
5455 p[ihi] = ((CH) >> 8) & 0xff; \
5456 p[ilo] = (CH) & 0xff; \
5457 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005458 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005459
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005460#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005461 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005462 if (s[i] >= 0x10000)
5463 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005464#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005465 /* 2 * (size + pairs + (byteorder == 0)) */
5466 if (size > PY_SSIZE_T_MAX ||
5467 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005468 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005469 nsize = size + pairs + (byteorder == 0);
5470 bytesize = nsize * 2;
5471 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005472 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005473 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474 if (v == NULL)
5475 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005476
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005477 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005479 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005480 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005481 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005482
5483 if (byteorder == -1) {
5484 /* force LE */
5485 ihi = 1;
5486 ilo = 0;
5487 }
5488 else if (byteorder == 1) {
5489 /* force BE */
5490 ihi = 0;
5491 ilo = 1;
5492 }
5493
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005494 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 Py_UNICODE ch = *s++;
5496 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005497#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 if (ch >= 0x10000) {
5499 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5500 ch = 0xD800 | ((ch-0x10000) >> 10);
5501 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005502#endif
Tim Peters772747b2001-08-09 22:21:55 +00005503 STORECHAR(ch);
5504 if (ch2)
5505 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005506 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005507
5508 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005509 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005510#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005511}
5512
Alexander Belopolsky40018472011-02-26 01:02:56 +00005513PyObject *
5514PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005515{
5516 if (!PyUnicode_Check(unicode)) {
5517 PyErr_BadArgument();
5518 return NULL;
5519 }
5520 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005521 PyUnicode_GET_SIZE(unicode),
5522 NULL,
5523 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005524}
5525
5526/* --- Unicode Escape Codec ----------------------------------------------- */
5527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005528/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5529 if all the escapes in the string make it still a valid ASCII string.
5530 Returns -1 if any escapes were found which cause the string to
5531 pop out of ASCII range. Otherwise returns the length of the
5532 required buffer to hold the string.
5533 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005534static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005535length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5536{
5537 const unsigned char *p = (const unsigned char *)s;
5538 const unsigned char *end = p + size;
5539 Py_ssize_t length = 0;
5540
5541 if (size < 0)
5542 return -1;
5543
5544 for (; p < end; ++p) {
5545 if (*p > 127) {
5546 /* Non-ASCII */
5547 return -1;
5548 }
5549 else if (*p != '\\') {
5550 /* Normal character */
5551 ++length;
5552 }
5553 else {
5554 /* Backslash-escape, check next char */
5555 ++p;
5556 /* Escape sequence reaches till end of string or
5557 non-ASCII follow-up. */
5558 if (p >= end || *p > 127)
5559 return -1;
5560 switch (*p) {
5561 case '\n':
5562 /* backslash + \n result in zero characters */
5563 break;
5564 case '\\': case '\'': case '\"':
5565 case 'b': case 'f': case 't':
5566 case 'n': case 'r': case 'v': case 'a':
5567 ++length;
5568 break;
5569 case '0': case '1': case '2': case '3':
5570 case '4': case '5': case '6': case '7':
5571 case 'x': case 'u': case 'U': case 'N':
5572 /* these do not guarantee ASCII characters */
5573 return -1;
5574 default:
5575 /* count the backslash + the other character */
5576 length += 2;
5577 }
5578 }
5579 }
5580 return length;
5581}
5582
5583/* Similar to PyUnicode_WRITE but either write into wstr field
5584 or treat string as ASCII. */
5585#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5586 do { \
5587 if ((kind) != PyUnicode_WCHAR_KIND) \
5588 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5589 else \
5590 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5591 } while (0)
5592
5593#define WRITE_WSTR(buf, index, value) \
5594 assert(kind == PyUnicode_WCHAR_KIND), \
5595 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5596
5597
Fredrik Lundh06d12682001-01-24 07:59:11 +00005598static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005599
Alexander Belopolsky40018472011-02-26 01:02:56 +00005600PyObject *
5601PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005602 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005603 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005605 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005606 Py_ssize_t startinpos;
5607 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005608 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005610 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005612 char* message;
5613 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005614 PyObject *errorHandler = NULL;
5615 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005616 Py_ssize_t ascii_length;
5617 Py_ssize_t i;
5618 int kind;
5619 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005621 ascii_length = length_of_escaped_ascii_string(s, size);
5622
5623 /* After length_of_escaped_ascii_string() there are two alternatives,
5624 either the string is pure ASCII with named escapes like \n, etc.
5625 and we determined it's exact size (common case)
5626 or it contains \x, \u, ... escape sequences. then we create a
5627 legacy wchar string and resize it at the end of this function. */
5628 if (ascii_length >= 0) {
5629 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5630 if (!v)
5631 goto onError;
5632 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5633 kind = PyUnicode_1BYTE_KIND;
5634 data = PyUnicode_DATA(v);
5635 }
5636 else {
5637 /* Escaped strings will always be longer than the resulting
5638 Unicode string, so we start with size here and then reduce the
5639 length after conversion to the true value.
5640 (but if the error callback returns a long replacement string
5641 we'll have to allocate more space) */
5642 v = _PyUnicode_New(size);
5643 if (!v)
5644 goto onError;
5645 kind = PyUnicode_WCHAR_KIND;
5646 data = PyUnicode_AS_UNICODE(v);
5647 }
5648
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649 if (size == 0)
5650 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005651 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005653
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 while (s < end) {
5655 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005656 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005657 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005659 if (kind == PyUnicode_WCHAR_KIND) {
5660 assert(i < _PyUnicode_WSTR_LENGTH(v));
5661 }
5662 else {
5663 /* The only case in which i == ascii_length is a backslash
5664 followed by a newline. */
5665 assert(i <= ascii_length);
5666 }
5667
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 /* Non-escape characters are interpreted as Unicode ordinals */
5669 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005670 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 continue;
5672 }
5673
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005674 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 /* \ - Escapes */
5676 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005677 c = *s++;
5678 if (s > end)
5679 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680
5681 if (kind == PyUnicode_WCHAR_KIND) {
5682 assert(i < _PyUnicode_WSTR_LENGTH(v));
5683 }
5684 else {
5685 /* The only case in which i == ascii_length is a backslash
5686 followed by a newline. */
5687 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5688 }
5689
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005690 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005694 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5695 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5696 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5697 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5698 /* FF */
5699 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5700 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5701 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5702 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5703 /* VT */
5704 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5705 /* BEL, not classic C */
5706 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709 case '0': case '1': case '2': case '3':
5710 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005711 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005712 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005713 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005714 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005715 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005717 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 break;
5719
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 /* hex escapes */
5721 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005723 digits = 2;
5724 message = "truncated \\xXX escape";
5725 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 digits = 4;
5730 message = "truncated \\uXXXX escape";
5731 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732
Benjamin Peterson29060642009-01-31 22:14:21 +00005733 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005734 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005735 digits = 8;
5736 message = "truncated \\UXXXXXXXX escape";
5737 hexescape:
5738 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005739 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005740 if (s+digits>end) {
5741 endinpos = size;
5742 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 errors, &errorHandler,
5744 "unicodeescape", "end of string in escape sequence",
5745 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005746 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005749 goto nextByte;
5750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005751 for (j = 0; j < digits; ++j) {
5752 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005753 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754 endinpos = (s+j+1)-starts;
5755 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 errors, &errorHandler,
5758 "unicodeescape", message,
5759 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005761 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005763 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005764 }
5765 chr = (chr<<4) & ~0xF;
5766 if (c >= '0' && c <= '9')
5767 chr += c - '0';
5768 else if (c >= 'a' && c <= 'f')
5769 chr += 10 + c - 'a';
5770 else
5771 chr += 10 + c - 'A';
5772 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005774 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 /* _decoding_error will have already written into the
5776 target buffer. */
5777 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005778 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005779 /* when we get here, chr is a 32-bit unicode character */
5780 if (chr <= 0xffff)
5781 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005782 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005784 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005785 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005786#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005787 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005788#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005789 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005790 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5791 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005792#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005793 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005795 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 errors, &errorHandler,
5798 "unicodeescape", "illegal Unicode character",
5799 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005800 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005801 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005802 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005803 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 break;
5805
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005807 case 'N':
5808 message = "malformed \\N character escape";
5809 if (ucnhash_CAPI == NULL) {
5810 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5812 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005813 if (ucnhash_CAPI == NULL)
5814 goto ucnhashError;
5815 }
5816 if (*s == '{') {
5817 const char *start = s+1;
5818 /* look for the closing brace */
5819 while (*s != '}' && s < end)
5820 s++;
5821 if (s > start && s < end && *s == '}') {
5822 /* found a name. look it up in the unicode database */
5823 message = "unknown Unicode character name";
5824 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005825 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
5826 &chr))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 goto store;
5828 }
5829 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005830 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005831 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005833 errors, &errorHandler,
5834 "unicodeescape", message,
5835 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005836 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005838 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839 break;
5840
5841 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005842 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005844 message = "\\ at end of string";
5845 s--;
5846 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005848 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005849 errors, &errorHandler,
5850 "unicodeescape", message,
5851 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005853 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005854 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005855 }
5856 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5858 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005859 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005861 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005864 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005865 /* Ensure the length prediction worked in case of ASCII strings */
5866 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5867
Victor Stinnerfe226c02011-10-03 03:52:20 +02005868 if (kind == PyUnicode_WCHAR_KIND)
5869 {
5870 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5871 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005872 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005873 Py_XDECREF(errorHandler);
5874 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005875#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005876 if (_PyUnicode_READY_REPLACE(&v)) {
5877 Py_DECREF(v);
5878 return NULL;
5879 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005880#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005881 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005883
Benjamin Peterson29060642009-01-31 22:14:21 +00005884 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005885 PyErr_SetString(
5886 PyExc_UnicodeError,
5887 "\\N escapes not supported (can't load unicodedata module)"
5888 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005889 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005890 Py_XDECREF(errorHandler);
5891 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005892 return NULL;
5893
Benjamin Peterson29060642009-01-31 22:14:21 +00005894 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005896 Py_XDECREF(errorHandler);
5897 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 return NULL;
5899}
5900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901#undef WRITE_ASCII_OR_WSTR
5902#undef WRITE_WSTR
5903
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904/* Return a Unicode-Escape string version of the Unicode object.
5905
5906 If quotes is true, the string is enclosed in u"" or u'' quotes as
5907 appropriate.
5908
5909*/
5910
Walter Dörwald79e913e2007-05-12 11:08:06 +00005911static const char *hexdigits = "0123456789abcdef";
5912
Alexander Belopolsky40018472011-02-26 01:02:56 +00005913PyObject *
5914PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005915 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005917 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005920#ifdef Py_UNICODE_WIDE
5921 const Py_ssize_t expandsize = 10;
5922#else
5923 const Py_ssize_t expandsize = 6;
5924#endif
5925
Thomas Wouters89f507f2006-12-13 04:49:30 +00005926 /* XXX(nnorwitz): rather than over-allocating, it would be
5927 better to choose a different scheme. Perhaps scan the
5928 first N-chars of the string and allocate based on that size.
5929 */
5930 /* Initial allocation is based on the longest-possible unichr
5931 escape.
5932
5933 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5934 unichr, so in this case it's the longest unichr escape. In
5935 narrow (UTF-16) builds this is five chars per source unichr
5936 since there are two unichrs in the surrogate pair, so in narrow
5937 (UTF-16) builds it's not the longest unichr escape.
5938
5939 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5940 so in the narrow (UTF-16) build case it's the longest unichr
5941 escape.
5942 */
5943
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005944 if (size == 0)
5945 return PyBytes_FromStringAndSize(NULL, 0);
5946
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005947 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005948 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005949
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005950 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005951 2
5952 + expandsize*size
5953 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 if (repr == NULL)
5955 return NULL;
5956
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958
Guido van Rossumd57fd912000-03-10 22:53:23 +00005959 while (size-- > 0) {
5960 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005961
Walter Dörwald79e913e2007-05-12 11:08:06 +00005962 /* Escape backslashes */
5963 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964 *p++ = '\\';
5965 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005966 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005967 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005968
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005969#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005970 /* Map 21-bit characters to '\U00xxxxxx' */
5971 else if (ch >= 0x10000) {
5972 *p++ = '\\';
5973 *p++ = 'U';
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 *p++ = hexdigits[(ch >> 28) & 0x0000000F];
5975 *p++ = hexdigits[(ch >> 24) & 0x0000000F];
5976 *p++ = hexdigits[(ch >> 20) & 0x0000000F];
5977 *p++ = hexdigits[(ch >> 16) & 0x0000000F];
5978 *p++ = hexdigits[(ch >> 12) & 0x0000000F];
5979 *p++ = hexdigits[(ch >> 8) & 0x0000000F];
5980 *p++ = hexdigits[(ch >> 4) & 0x0000000F];
5981 *p++ = hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005982 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005983 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005984#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5986 else if (ch >= 0xD800 && ch < 0xDC00) {
5987 Py_UNICODE ch2;
5988 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005989
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 ch2 = *s++;
5991 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005992 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5994 *p++ = '\\';
5995 *p++ = 'U';
5996 *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
5997 *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
5998 *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
5999 *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
6000 *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
6001 *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
6002 *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
6003 *p++ = hexdigits[ucs & 0x0000000F];
6004 continue;
6005 }
6006 /* Fall through: isolated surrogates are copied as-is */
6007 s--;
6008 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006009 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006010#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006011
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006013 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014 *p++ = '\\';
6015 *p++ = 'u';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006016 *p++ = hexdigits[(ch >> 12) & 0x000F];
6017 *p++ = hexdigits[(ch >> 8) & 0x000F];
6018 *p++ = hexdigits[(ch >> 4) & 0x000F];
6019 *p++ = hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006021
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006022 /* Map special whitespace to '\t', \n', '\r' */
6023 else if (ch == '\t') {
6024 *p++ = '\\';
6025 *p++ = 't';
6026 }
6027 else if (ch == '\n') {
6028 *p++ = '\\';
6029 *p++ = 'n';
6030 }
6031 else if (ch == '\r') {
6032 *p++ = '\\';
6033 *p++ = 'r';
6034 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006035
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006036 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006037 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006039 *p++ = 'x';
Walter Dörwald79e913e2007-05-12 11:08:06 +00006040 *p++ = hexdigits[(ch >> 4) & 0x000F];
6041 *p++ = hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006042 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006043
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 /* Copy everything else as-is */
6045 else
6046 *p++ = (char) ch;
6047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006049 assert(p - PyBytes_AS_STRING(repr) > 0);
6050 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6051 return NULL;
6052 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053}
6054
Alexander Belopolsky40018472011-02-26 01:02:56 +00006055PyObject *
6056PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006058 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 if (!PyUnicode_Check(unicode)) {
6060 PyErr_BadArgument();
6061 return NULL;
6062 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006063 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6064 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006065 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066}
6067
6068/* --- Raw Unicode Escape Codec ------------------------------------------- */
6069
Alexander Belopolsky40018472011-02-26 01:02:56 +00006070PyObject *
6071PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006072 Py_ssize_t size,
6073 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006075 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006076 Py_ssize_t startinpos;
6077 Py_ssize_t endinpos;
6078 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006080 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 const char *end;
6082 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006083 PyObject *errorHandler = NULL;
6084 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006085
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 /* Escaped strings will always be longer than the resulting
6087 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 length after conversion to the true value. (But decoding error
6089 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 v = _PyUnicode_New(size);
6091 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006095 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096 end = s + size;
6097 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 unsigned char c;
6099 Py_UCS4 x;
6100 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006101 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006102
Benjamin Peterson29060642009-01-31 22:14:21 +00006103 /* Non-escape characters are interpreted as Unicode ordinals */
6104 if (*s != '\\') {
6105 *p++ = (unsigned char)*s++;
6106 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006107 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 startinpos = s-starts;
6109
6110 /* \u-escapes are only interpreted iff the number of leading
6111 backslashes if odd */
6112 bs = s;
6113 for (;s < end;) {
6114 if (*s != '\\')
6115 break;
6116 *p++ = (unsigned char)*s++;
6117 }
6118 if (((s - bs) & 1) == 0 ||
6119 s >= end ||
6120 (*s != 'u' && *s != 'U')) {
6121 continue;
6122 }
6123 p--;
6124 count = *s=='u' ? 4 : 8;
6125 s++;
6126
6127 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6128 outpos = p-PyUnicode_AS_UNICODE(v);
6129 for (x = 0, i = 0; i < count; ++i, ++s) {
6130 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006131 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 endinpos = s-starts;
6133 if (unicode_decode_call_errorhandler(
6134 errors, &errorHandler,
6135 "rawunicodeescape", "truncated \\uXXXX",
6136 &starts, &end, &startinpos, &endinpos, &exc, &s,
6137 &v, &outpos, &p))
6138 goto onError;
6139 goto nextByte;
6140 }
6141 x = (x<<4) & ~0xF;
6142 if (c >= '0' && c <= '9')
6143 x += c - '0';
6144 else if (c >= 'a' && c <= 'f')
6145 x += 10 + c - 'a';
6146 else
6147 x += 10 + c - 'A';
6148 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006149 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006150 /* UCS-2 character */
6151 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006152 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 /* UCS-4 character. Either store directly, or as
6154 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006155#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006157#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 x -= 0x10000L;
6159 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6160 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006161#endif
6162 } else {
6163 endinpos = s-starts;
6164 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006165 if (unicode_decode_call_errorhandler(
6166 errors, &errorHandler,
6167 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006168 &starts, &end, &startinpos, &endinpos, &exc, &s,
6169 &v, &outpos, &p))
6170 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006171 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 nextByte:
6173 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006175 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006177 Py_XDECREF(errorHandler);
6178 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006179#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006180 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006181 Py_DECREF(v);
6182 return NULL;
6183 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006184#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006185 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006187
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006190 Py_XDECREF(errorHandler);
6191 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 return NULL;
6193}
6194
Alexander Belopolsky40018472011-02-26 01:02:56 +00006195PyObject *
6196PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006197 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006199 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 char *p;
6201 char *q;
6202
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006203#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006204 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006205#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006206 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006207#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006208
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006209 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006211
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006212 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 if (repr == NULL)
6214 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006215 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006216 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006218 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 while (size-- > 0) {
6220 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006221#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006222 /* Map 32-bit characters to '\Uxxxxxxxx' */
6223 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224 *p++ = '\\';
6225 *p++ = 'U';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006226 *p++ = hexdigits[(ch >> 28) & 0xf];
6227 *p++ = hexdigits[(ch >> 24) & 0xf];
6228 *p++ = hexdigits[(ch >> 20) & 0xf];
6229 *p++ = hexdigits[(ch >> 16) & 0xf];
6230 *p++ = hexdigits[(ch >> 12) & 0xf];
6231 *p++ = hexdigits[(ch >> 8) & 0xf];
6232 *p++ = hexdigits[(ch >> 4) & 0xf];
6233 *p++ = hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006234 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006235 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006236#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6238 if (ch >= 0xD800 && ch < 0xDC00) {
6239 Py_UNICODE ch2;
6240 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 ch2 = *s++;
6243 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006244 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6246 *p++ = '\\';
6247 *p++ = 'U';
6248 *p++ = hexdigits[(ucs >> 28) & 0xf];
6249 *p++ = hexdigits[(ucs >> 24) & 0xf];
6250 *p++ = hexdigits[(ucs >> 20) & 0xf];
6251 *p++ = hexdigits[(ucs >> 16) & 0xf];
6252 *p++ = hexdigits[(ucs >> 12) & 0xf];
6253 *p++ = hexdigits[(ucs >> 8) & 0xf];
6254 *p++ = hexdigits[(ucs >> 4) & 0xf];
6255 *p++ = hexdigits[ucs & 0xf];
6256 continue;
6257 }
6258 /* Fall through: isolated surrogates are copied as-is */
6259 s--;
6260 size++;
6261 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006262#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 /* Map 16-bit characters to '\uxxxx' */
6264 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006265 *p++ = '\\';
6266 *p++ = 'u';
Walter Dörwalddb5d33e2007-05-12 11:13:47 +00006267 *p++ = hexdigits[(ch >> 12) & 0xf];
6268 *p++ = hexdigits[(ch >> 8) & 0xf];
6269 *p++ = hexdigits[(ch >> 4) & 0xf];
6270 *p++ = hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 /* Copy everything else as-is */
6273 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274 *p++ = (char) ch;
6275 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006276 size = p - q;
6277
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006278 assert(size > 0);
6279 if (_PyBytes_Resize(&repr, size) < 0)
6280 return NULL;
6281 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282}
6283
Alexander Belopolsky40018472011-02-26 01:02:56 +00006284PyObject *
6285PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006286{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006287 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006289 PyErr_BadArgument();
6290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006292 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6293 PyUnicode_GET_SIZE(unicode));
6294
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006295 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296}
6297
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006298/* --- Unicode Internal Codec ------------------------------------------- */
6299
Alexander Belopolsky40018472011-02-26 01:02:56 +00006300PyObject *
6301_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006302 Py_ssize_t size,
6303 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006304{
6305 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006306 Py_ssize_t startinpos;
6307 Py_ssize_t endinpos;
6308 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006309 PyUnicodeObject *v;
6310 Py_UNICODE *p;
6311 const char *end;
6312 const char *reason;
6313 PyObject *errorHandler = NULL;
6314 PyObject *exc = NULL;
6315
Neal Norwitzd43069c2006-01-08 01:12:10 +00006316#ifdef Py_UNICODE_WIDE
6317 Py_UNICODE unimax = PyUnicode_GetMax();
6318#endif
6319
Thomas Wouters89f507f2006-12-13 04:49:30 +00006320 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006321 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6322 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006324 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6325 as string was created with the old API. */
6326 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006327 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 p = PyUnicode_AS_UNICODE(v);
6329 end = s + size;
6330
6331 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006332 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 /* We have to sanity check the raw data, otherwise doom looms for
6334 some malformed UCS-4 data. */
6335 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006336#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006338#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 end-s < Py_UNICODE_SIZE
6340 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006342 startinpos = s - starts;
6343 if (end-s < Py_UNICODE_SIZE) {
6344 endinpos = end-starts;
6345 reason = "truncated input";
6346 }
6347 else {
6348 endinpos = s - starts + Py_UNICODE_SIZE;
6349 reason = "illegal code point (> 0x10FFFF)";
6350 }
6351 outpos = p - PyUnicode_AS_UNICODE(v);
6352 if (unicode_decode_call_errorhandler(
6353 errors, &errorHandler,
6354 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006355 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006356 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006357 goto onError;
6358 }
6359 }
6360 else {
6361 p++;
6362 s += Py_UNICODE_SIZE;
6363 }
6364 }
6365
Victor Stinnerfe226c02011-10-03 03:52:20 +02006366 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006367 goto onError;
6368 Py_XDECREF(errorHandler);
6369 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006370#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006371 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006372 Py_DECREF(v);
6373 return NULL;
6374 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006375#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006376 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006377 return (PyObject *)v;
6378
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006380 Py_XDECREF(v);
6381 Py_XDECREF(errorHandler);
6382 Py_XDECREF(exc);
6383 return NULL;
6384}
6385
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386/* --- Latin-1 Codec ------------------------------------------------------ */
6387
Alexander Belopolsky40018472011-02-26 01:02:56 +00006388PyObject *
6389PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006390 Py_ssize_t size,
6391 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006392{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006394 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395}
6396
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006398static void
6399make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006400 const char *encoding,
6401 const Py_UNICODE *unicode, Py_ssize_t size,
6402 Py_ssize_t startpos, Py_ssize_t endpos,
6403 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 *exceptionObject = PyUnicodeEncodeError_Create(
6407 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408 }
6409 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6411 goto onError;
6412 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6413 goto onError;
6414 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6415 goto onError;
6416 return;
6417 onError:
6418 Py_DECREF(*exceptionObject);
6419 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006420 }
6421}
6422
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006424static void
6425raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006426 const char *encoding,
6427 const Py_UNICODE *unicode, Py_ssize_t size,
6428 Py_ssize_t startpos, Py_ssize_t endpos,
6429 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430{
6431 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006433 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435}
6436
6437/* error handling callback helper:
6438 build arguments, call the callback and check the arguments,
6439 put the result into newpos and return the replacement string, which
6440 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006441static PyObject *
6442unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006443 PyObject **errorHandler,
6444 const char *encoding, const char *reason,
6445 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6446 Py_ssize_t startpos, Py_ssize_t endpos,
6447 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006449 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450
6451 PyObject *restuple;
6452 PyObject *resunicode;
6453
6454 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006456 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458 }
6459
6460 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464
6465 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006466 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006470 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 Py_DECREF(restuple);
6472 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006473 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006474 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 &resunicode, newpos)) {
6476 Py_DECREF(restuple);
6477 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006479 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6480 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6481 Py_DECREF(restuple);
6482 return NULL;
6483 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006486 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6488 Py_DECREF(restuple);
6489 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006490 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 Py_INCREF(resunicode);
6492 Py_DECREF(restuple);
6493 return resunicode;
6494}
6495
Alexander Belopolsky40018472011-02-26 01:02:56 +00006496static PyObject *
6497unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006498 Py_ssize_t size,
6499 const char *errors,
6500 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006501{
6502 /* output object */
6503 PyObject *res;
6504 /* pointers to the beginning and end+1 of input */
6505 const Py_UNICODE *startp = p;
6506 const Py_UNICODE *endp = p + size;
6507 /* pointer to the beginning of the unencodable characters */
6508 /* const Py_UNICODE *badp = NULL; */
6509 /* pointer into the output */
6510 char *str;
6511 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006512 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006513 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6514 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 PyObject *errorHandler = NULL;
6516 PyObject *exc = NULL;
6517 /* the following variable is used for caching string comparisons
6518 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6519 int known_errorHandler = -1;
6520
6521 /* allocate enough for a simple encoding without
6522 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006523 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006524 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006525 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006526 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006527 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006528 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006529 ressize = size;
6530
6531 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006533
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 /* can we encode this? */
6535 if (c<limit) {
6536 /* no overflow check, because we know that the space is enough */
6537 *str++ = (char)c;
6538 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006539 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 else {
6541 Py_ssize_t unicodepos = p-startp;
6542 Py_ssize_t requiredsize;
6543 PyObject *repunicode;
6544 Py_ssize_t repsize;
6545 Py_ssize_t newpos;
6546 Py_ssize_t respos;
6547 Py_UNICODE *uni2;
6548 /* startpos for collecting unencodable chars */
6549 const Py_UNICODE *collstart = p;
6550 const Py_UNICODE *collend = p;
6551 /* find all unecodable characters */
6552 while ((collend < endp) && ((*collend)>=limit))
6553 ++collend;
6554 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6555 if (known_errorHandler==-1) {
6556 if ((errors==NULL) || (!strcmp(errors, "strict")))
6557 known_errorHandler = 1;
6558 else if (!strcmp(errors, "replace"))
6559 known_errorHandler = 2;
6560 else if (!strcmp(errors, "ignore"))
6561 known_errorHandler = 3;
6562 else if (!strcmp(errors, "xmlcharrefreplace"))
6563 known_errorHandler = 4;
6564 else
6565 known_errorHandler = 0;
6566 }
6567 switch (known_errorHandler) {
6568 case 1: /* strict */
6569 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6570 goto onError;
6571 case 2: /* replace */
6572 while (collstart++<collend)
6573 *str++ = '?'; /* fall through */
6574 case 3: /* ignore */
6575 p = collend;
6576 break;
6577 case 4: /* xmlcharrefreplace */
6578 respos = str - PyBytes_AS_STRING(res);
6579 /* determine replacement size (temporarily (mis)uses p) */
6580 for (p = collstart, repsize = 0; p < collend; ++p) {
6581 if (*p<10)
6582 repsize += 2+1+1;
6583 else if (*p<100)
6584 repsize += 2+2+1;
6585 else if (*p<1000)
6586 repsize += 2+3+1;
6587 else if (*p<10000)
6588 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006589#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 else
6591 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006592#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006593 else if (*p<100000)
6594 repsize += 2+5+1;
6595 else if (*p<1000000)
6596 repsize += 2+6+1;
6597 else
6598 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006599#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 }
6601 requiredsize = respos+repsize+(endp-collend);
6602 if (requiredsize > ressize) {
6603 if (requiredsize<2*ressize)
6604 requiredsize = 2*ressize;
6605 if (_PyBytes_Resize(&res, requiredsize))
6606 goto onError;
6607 str = PyBytes_AS_STRING(res) + respos;
6608 ressize = requiredsize;
6609 }
6610 /* generate replacement (temporarily (mis)uses p) */
6611 for (p = collstart; p < collend; ++p) {
6612 str += sprintf(str, "&#%d;", (int)*p);
6613 }
6614 p = collend;
6615 break;
6616 default:
6617 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6618 encoding, reason, startp, size, &exc,
6619 collstart-startp, collend-startp, &newpos);
6620 if (repunicode == NULL)
6621 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006622 if (PyBytes_Check(repunicode)) {
6623 /* Directly copy bytes result to output. */
6624 repsize = PyBytes_Size(repunicode);
6625 if (repsize > 1) {
6626 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006627 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006628 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6629 Py_DECREF(repunicode);
6630 goto onError;
6631 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006632 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006633 ressize += repsize-1;
6634 }
6635 memcpy(str, PyBytes_AsString(repunicode), repsize);
6636 str += repsize;
6637 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006638 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006639 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006640 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 /* need more space? (at least enough for what we
6642 have+the replacement+the rest of the string, so
6643 we won't have to check space for encodable characters) */
6644 respos = str - PyBytes_AS_STRING(res);
6645 repsize = PyUnicode_GET_SIZE(repunicode);
6646 requiredsize = respos+repsize+(endp-collend);
6647 if (requiredsize > ressize) {
6648 if (requiredsize<2*ressize)
6649 requiredsize = 2*ressize;
6650 if (_PyBytes_Resize(&res, requiredsize)) {
6651 Py_DECREF(repunicode);
6652 goto onError;
6653 }
6654 str = PyBytes_AS_STRING(res) + respos;
6655 ressize = requiredsize;
6656 }
6657 /* check if there is anything unencodable in the replacement
6658 and copy it to the output */
6659 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6660 c = *uni2;
6661 if (c >= limit) {
6662 raise_encode_exception(&exc, encoding, startp, size,
6663 unicodepos, unicodepos+1, reason);
6664 Py_DECREF(repunicode);
6665 goto onError;
6666 }
6667 *str = (char)c;
6668 }
6669 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006670 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006671 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006672 }
6673 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006674 /* Resize if we allocated to much */
6675 size = str - PyBytes_AS_STRING(res);
6676 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006677 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006678 if (_PyBytes_Resize(&res, size) < 0)
6679 goto onError;
6680 }
6681
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006682 Py_XDECREF(errorHandler);
6683 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006684 return res;
6685
6686 onError:
6687 Py_XDECREF(res);
6688 Py_XDECREF(errorHandler);
6689 Py_XDECREF(exc);
6690 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691}
6692
Alexander Belopolsky40018472011-02-26 01:02:56 +00006693PyObject *
6694PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006695 Py_ssize_t size,
6696 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006697{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006699}
6700
Alexander Belopolsky40018472011-02-26 01:02:56 +00006701PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006702_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703{
6704 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 PyErr_BadArgument();
6706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006708 if (PyUnicode_READY(unicode) == -1)
6709 return NULL;
6710 /* Fast path: if it is a one-byte string, construct
6711 bytes object directly. */
6712 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6713 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6714 PyUnicode_GET_LENGTH(unicode));
6715 /* Non-Latin-1 characters present. Defer to above function to
6716 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006717 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006719 errors);
6720}
6721
6722PyObject*
6723PyUnicode_AsLatin1String(PyObject *unicode)
6724{
6725 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006726}
6727
6728/* --- 7-bit ASCII Codec -------------------------------------------------- */
6729
Alexander Belopolsky40018472011-02-26 01:02:56 +00006730PyObject *
6731PyUnicode_DecodeASCII(const char *s,
6732 Py_ssize_t size,
6733 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006734{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006737 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006738 Py_ssize_t startinpos;
6739 Py_ssize_t endinpos;
6740 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006741 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006742 int has_error;
6743 const unsigned char *p = (const unsigned char *)s;
6744 const unsigned char *end = p + size;
6745 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746 PyObject *errorHandler = NULL;
6747 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006748
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006750 if (size == 1 && (unsigned char)s[0] < 128)
6751 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006752
Victor Stinner702c7342011-10-05 13:50:52 +02006753 has_error = 0;
6754 while (p < end && !has_error) {
6755 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6756 an explanation. */
6757 if (!((size_t) p & LONG_PTR_MASK)) {
6758 /* Help register allocation */
6759 register const unsigned char *_p = p;
6760 while (_p < aligned_end) {
6761 unsigned long value = *(unsigned long *) _p;
6762 if (value & ASCII_CHAR_MASK) {
6763 has_error = 1;
6764 break;
6765 }
6766 _p += SIZEOF_LONG;
6767 }
6768 if (_p == end)
6769 break;
6770 if (has_error)
6771 break;
6772 p = _p;
6773 }
6774 if (*p & 0x80) {
6775 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006776 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006777 }
6778 else {
6779 ++p;
6780 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006781 }
Victor Stinner702c7342011-10-05 13:50:52 +02006782 if (!has_error)
6783 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006784
Guido van Rossumd57fd912000-03-10 22:53:23 +00006785 v = _PyUnicode_New(size);
6786 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006789 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006790 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006791 e = s + size;
6792 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 register unsigned char c = (unsigned char)*s;
6794 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006795 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 ++s;
6797 }
6798 else {
6799 startinpos = s-starts;
6800 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006801 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 if (unicode_decode_call_errorhandler(
6803 errors, &errorHandler,
6804 "ascii", "ordinal not in range(128)",
6805 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006806 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 goto onError;
6808 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809 }
Victor Stinner702c7342011-10-05 13:50:52 +02006810 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6811 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006813 Py_XDECREF(errorHandler);
6814 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006815#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006816 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006817 Py_DECREF(v);
6818 return NULL;
6819 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006820#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006821 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006822 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006823
Benjamin Peterson29060642009-01-31 22:14:21 +00006824 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006825 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006826 Py_XDECREF(errorHandler);
6827 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006828 return NULL;
6829}
6830
Alexander Belopolsky40018472011-02-26 01:02:56 +00006831PyObject *
6832PyUnicode_EncodeASCII(const Py_UNICODE *p,
6833 Py_ssize_t size,
6834 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006836 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006837}
6838
Alexander Belopolsky40018472011-02-26 01:02:56 +00006839PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006840_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841{
6842 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006843 PyErr_BadArgument();
6844 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006846 if (PyUnicode_READY(unicode) == -1)
6847 return NULL;
6848 /* Fast path: if it is an ASCII-only string, construct bytes object
6849 directly. Else defer to above function to raise the exception. */
6850 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6851 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6852 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006853 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006855 errors);
6856}
6857
6858PyObject *
6859PyUnicode_AsASCIIString(PyObject *unicode)
6860{
6861 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862}
6863
Victor Stinner99b95382011-07-04 14:23:54 +02006864#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006865
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006866/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006867
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006868#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869#define NEED_RETRY
6870#endif
6871
6872/* XXX This code is limited to "true" double-byte encodings, as
6873 a) it assumes an incomplete character consists of a single byte, and
6874 b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 encodings, see IsDBCSLeadByteEx documentation. */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006876
Alexander Belopolsky40018472011-02-26 01:02:56 +00006877static int
6878is_dbcs_lead_byte(const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006879{
6880 const char *curr = s + offset;
6881
6882 if (IsDBCSLeadByte(*curr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 const char *prev = CharPrev(s, curr);
6884 return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006885 }
6886 return 0;
6887}
6888
6889/*
6890 * Decode MBCS string into unicode object. If 'final' is set, converts
6891 * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
6892 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006893static int
6894decode_mbcs(PyUnicodeObject **v,
6895 const char *s, /* MBCS string */
6896 int size, /* sizeof MBCS string */
6897 int final,
6898 const char *errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899{
6900 Py_UNICODE *p;
Victor Stinner554f3f02010-06-16 23:33:54 +00006901 Py_ssize_t n;
6902 DWORD usize;
6903 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904
6905 assert(size >= 0);
6906
Victor Stinner554f3f02010-06-16 23:33:54 +00006907 /* check and handle 'errors' arg */
6908 if (errors==NULL || strcmp(errors, "strict")==0)
6909 flags = MB_ERR_INVALID_CHARS;
6910 else if (strcmp(errors, "ignore")==0)
6911 flags = 0;
6912 else {
6913 PyErr_Format(PyExc_ValueError,
6914 "mbcs encoding does not support errors='%s'",
6915 errors);
6916 return -1;
6917 }
6918
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006919 /* Skip trailing lead-byte unless 'final' is set */
6920 if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006921 --size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006922
6923 /* First get the size of the result */
6924 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00006925 usize = MultiByteToWideChar(CP_ACP, flags, s, size, NULL, 0);
6926 if (usize==0)
6927 goto mbcs_decode_error;
6928 } else
6929 usize = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006930
6931 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006932 /* Create unicode object */
6933 *v = _PyUnicode_New(usize);
6934 if (*v == NULL)
6935 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00006936 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937 }
6938 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 /* Extend unicode object */
6940 n = PyUnicode_GET_SIZE(*v);
Victor Stinner2fd82272011-10-03 04:06:05 +02006941 if (PyUnicode_Resize((PyObject**)v, n + usize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006942 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943 }
6944
6945 /* Do the conversion */
Victor Stinner554f3f02010-06-16 23:33:54 +00006946 if (usize > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006947 p = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00006948 if (0 == MultiByteToWideChar(CP_ACP, flags, s, size, p, usize)) {
6949 goto mbcs_decode_error;
Benjamin Peterson29060642009-01-31 22:14:21 +00006950 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006952 return size;
Victor Stinner554f3f02010-06-16 23:33:54 +00006953
6954mbcs_decode_error:
6955 /* If the last error was ERROR_NO_UNICODE_TRANSLATION, then
6956 we raise a UnicodeDecodeError - else it is a 'generic'
6957 windows error
6958 */
6959 if (GetLastError()==ERROR_NO_UNICODE_TRANSLATION) {
6960 /* Ideally, we should get reason from FormatMessage - this
6961 is the Windows 2000 English version of the message
6962 */
6963 PyObject *exc = NULL;
6964 const char *reason = "No mapping for the Unicode character exists "
6965 "in the target multi-byte code page.";
6966 make_decode_exception(&exc, "mbcs", s, size, 0, 0, reason);
6967 if (exc != NULL) {
6968 PyCodec_StrictErrors(exc);
6969 Py_DECREF(exc);
6970 }
6971 } else {
6972 PyErr_SetFromWindowsErrWithFilename(0, NULL);
6973 }
6974 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006975}
6976
Alexander Belopolsky40018472011-02-26 01:02:56 +00006977PyObject *
6978PyUnicode_DecodeMBCSStateful(const char *s,
6979 Py_ssize_t size,
6980 const char *errors,
6981 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006982{
6983 PyUnicodeObject *v = NULL;
6984 int done;
6985
6986 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006988
6989#ifdef NEED_RETRY
6990 retry:
6991 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00006992 done = decode_mbcs(&v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006993 else
6994#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00006995 done = decode_mbcs(&v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006996
6997 if (done < 0) {
6998 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006999 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007000 }
7001
7002 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007003 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004
7005#ifdef NEED_RETRY
7006 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 s += done;
7008 size -= done;
7009 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010 }
7011#endif
Victor Stinner17efeed2011-10-04 20:05:46 +02007012#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007013 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007014 Py_DECREF(v);
7015 return NULL;
7016 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007017#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007018 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019 return (PyObject *)v;
7020}
7021
Alexander Belopolsky40018472011-02-26 01:02:56 +00007022PyObject *
7023PyUnicode_DecodeMBCS(const char *s,
7024 Py_ssize_t size,
7025 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007026{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7028}
7029
7030/*
7031 * Convert unicode into string object (MBCS).
7032 * Returns 0 if succeed, -1 otherwise.
7033 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007034static int
7035encode_mbcs(PyObject **repr,
7036 const Py_UNICODE *p, /* unicode */
7037 int size, /* size of unicode */
7038 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039{
Victor Stinner554f3f02010-06-16 23:33:54 +00007040 BOOL usedDefaultChar = FALSE;
7041 BOOL *pusedDefaultChar;
7042 int mbcssize;
7043 Py_ssize_t n;
7044 PyObject *exc = NULL;
7045 DWORD flags;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046
7047 assert(size >= 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007048
Victor Stinner554f3f02010-06-16 23:33:54 +00007049 /* check and handle 'errors' arg */
7050 if (errors==NULL || strcmp(errors, "strict")==0) {
7051 flags = WC_NO_BEST_FIT_CHARS;
7052 pusedDefaultChar = &usedDefaultChar;
7053 } else if (strcmp(errors, "replace")==0) {
7054 flags = 0;
7055 pusedDefaultChar = NULL;
7056 } else {
7057 PyErr_Format(PyExc_ValueError,
7058 "mbcs encoding does not support errors='%s'",
7059 errors);
7060 return -1;
7061 }
7062
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007063 /* First get the size of the result */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064 if (size > 0) {
Victor Stinner554f3f02010-06-16 23:33:54 +00007065 mbcssize = WideCharToMultiByte(CP_ACP, flags, p, size, NULL, 0,
7066 NULL, pusedDefaultChar);
Benjamin Peterson29060642009-01-31 22:14:21 +00007067 if (mbcssize == 0) {
7068 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7069 return -1;
7070 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007071 /* If we used a default char, then we failed! */
7072 if (pusedDefaultChar && *pusedDefaultChar)
7073 goto mbcs_encode_error;
7074 } else {
7075 mbcssize = 0;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007076 }
7077
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078 if (*repr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007079 /* Create string object */
7080 *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
7081 if (*repr == NULL)
7082 return -1;
Victor Stinner554f3f02010-06-16 23:33:54 +00007083 n = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084 }
7085 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 /* Extend string object */
7087 n = PyBytes_Size(*repr);
7088 if (_PyBytes_Resize(repr, n + mbcssize) < 0)
7089 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090 }
7091
7092 /* Do the conversion */
7093 if (size > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 char *s = PyBytes_AS_STRING(*repr) + n;
Victor Stinner554f3f02010-06-16 23:33:54 +00007095 if (0 == WideCharToMultiByte(CP_ACP, flags, p, size, s, mbcssize,
7096 NULL, pusedDefaultChar)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007097 PyErr_SetFromWindowsErrWithFilename(0, NULL);
7098 return -1;
7099 }
Victor Stinner554f3f02010-06-16 23:33:54 +00007100 if (pusedDefaultChar && *pusedDefaultChar)
7101 goto mbcs_encode_error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007104
7105mbcs_encode_error:
7106 raise_encode_exception(&exc, "mbcs", p, size, 0, 0, "invalid character");
7107 Py_XDECREF(exc);
7108 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007109}
7110
Alexander Belopolsky40018472011-02-26 01:02:56 +00007111PyObject *
7112PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7113 Py_ssize_t size,
7114 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007115{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116 PyObject *repr = NULL;
7117 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007118
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007119#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007120 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007121 if (size > INT_MAX)
Victor Stinner554f3f02010-06-16 23:33:54 +00007122 ret = encode_mbcs(&repr, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123 else
7124#endif
Victor Stinner554f3f02010-06-16 23:33:54 +00007125 ret = encode_mbcs(&repr, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007126
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007127 if (ret < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007128 Py_XDECREF(repr);
7129 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007130 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007131
7132#ifdef NEED_RETRY
7133 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007134 p += INT_MAX;
7135 size -= INT_MAX;
7136 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007137 }
7138#endif
7139
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007140 return repr;
7141}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007142
Alexander Belopolsky40018472011-02-26 01:02:56 +00007143PyObject *
7144PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007145{
7146 if (!PyUnicode_Check(unicode)) {
7147 PyErr_BadArgument();
7148 return NULL;
7149 }
7150 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007151 PyUnicode_GET_SIZE(unicode),
7152 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007153}
7154
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007155#undef NEED_RETRY
7156
Victor Stinner99b95382011-07-04 14:23:54 +02007157#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007158
Guido van Rossumd57fd912000-03-10 22:53:23 +00007159/* --- Character Mapping Codec -------------------------------------------- */
7160
Alexander Belopolsky40018472011-02-26 01:02:56 +00007161PyObject *
7162PyUnicode_DecodeCharmap(const char *s,
7163 Py_ssize_t size,
7164 PyObject *mapping,
7165 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007166{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007167 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007168 Py_ssize_t startinpos;
7169 Py_ssize_t endinpos;
7170 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007171 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007172 PyUnicodeObject *v;
7173 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007174 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007175 PyObject *errorHandler = NULL;
7176 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007177 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007178 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007179
Guido van Rossumd57fd912000-03-10 22:53:23 +00007180 /* Default to Latin-1 */
7181 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007182 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007183
7184 v = _PyUnicode_New(size);
7185 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007186 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007187 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007189 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007190 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007191 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007192 mapstring = PyUnicode_AS_UNICODE(mapping);
7193 maplen = PyUnicode_GET_SIZE(mapping);
7194 while (s < e) {
7195 unsigned char ch = *s;
7196 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007197
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 if (ch < maplen)
7199 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007200
Benjamin Peterson29060642009-01-31 22:14:21 +00007201 if (x == 0xfffe) {
7202 /* undefined mapping */
7203 outpos = p-PyUnicode_AS_UNICODE(v);
7204 startinpos = s-starts;
7205 endinpos = startinpos+1;
7206 if (unicode_decode_call_errorhandler(
7207 errors, &errorHandler,
7208 "charmap", "character maps to <undefined>",
7209 &starts, &e, &startinpos, &endinpos, &exc, &s,
7210 &v, &outpos, &p)) {
7211 goto onError;
7212 }
7213 continue;
7214 }
7215 *p++ = x;
7216 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007217 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007218 }
7219 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007220 while (s < e) {
7221 unsigned char ch = *s;
7222 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007223
Benjamin Peterson29060642009-01-31 22:14:21 +00007224 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7225 w = PyLong_FromLong((long)ch);
7226 if (w == NULL)
7227 goto onError;
7228 x = PyObject_GetItem(mapping, w);
7229 Py_DECREF(w);
7230 if (x == NULL) {
7231 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7232 /* No mapping found means: mapping is undefined. */
7233 PyErr_Clear();
7234 x = Py_None;
7235 Py_INCREF(x);
7236 } else
7237 goto onError;
7238 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007239
Benjamin Peterson29060642009-01-31 22:14:21 +00007240 /* Apply mapping */
7241 if (PyLong_Check(x)) {
7242 long value = PyLong_AS_LONG(x);
7243 if (value < 0 || value > 65535) {
7244 PyErr_SetString(PyExc_TypeError,
7245 "character mapping must be in range(65536)");
7246 Py_DECREF(x);
7247 goto onError;
7248 }
7249 *p++ = (Py_UNICODE)value;
7250 }
7251 else if (x == Py_None) {
7252 /* undefined mapping */
7253 outpos = p-PyUnicode_AS_UNICODE(v);
7254 startinpos = s-starts;
7255 endinpos = startinpos+1;
7256 if (unicode_decode_call_errorhandler(
7257 errors, &errorHandler,
7258 "charmap", "character maps to <undefined>",
7259 &starts, &e, &startinpos, &endinpos, &exc, &s,
7260 &v, &outpos, &p)) {
7261 Py_DECREF(x);
7262 goto onError;
7263 }
7264 Py_DECREF(x);
7265 continue;
7266 }
7267 else if (PyUnicode_Check(x)) {
7268 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007269
Benjamin Peterson29060642009-01-31 22:14:21 +00007270 if (targetsize == 1)
7271 /* 1-1 mapping */
7272 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007273
Benjamin Peterson29060642009-01-31 22:14:21 +00007274 else if (targetsize > 1) {
7275 /* 1-n mapping */
7276 if (targetsize > extrachars) {
7277 /* resize first */
7278 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7279 Py_ssize_t needed = (targetsize - extrachars) + \
7280 (targetsize << 2);
7281 extrachars += needed;
7282 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007283 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007284 PyUnicode_GET_SIZE(v) + needed) < 0) {
7285 Py_DECREF(x);
7286 goto onError;
7287 }
7288 p = PyUnicode_AS_UNICODE(v) + oldpos;
7289 }
7290 Py_UNICODE_COPY(p,
7291 PyUnicode_AS_UNICODE(x),
7292 targetsize);
7293 p += targetsize;
7294 extrachars -= targetsize;
7295 }
7296 /* 1-0 mapping: skip the character */
7297 }
7298 else {
7299 /* wrong return value */
7300 PyErr_SetString(PyExc_TypeError,
7301 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007302 Py_DECREF(x);
7303 goto onError;
7304 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007305 Py_DECREF(x);
7306 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007307 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007308 }
7309 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007310 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007311 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007312 Py_XDECREF(errorHandler);
7313 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007314#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007315 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007316 Py_DECREF(v);
7317 return NULL;
7318 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007319#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007320 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007321 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007322
Benjamin Peterson29060642009-01-31 22:14:21 +00007323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007324 Py_XDECREF(errorHandler);
7325 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007326 Py_XDECREF(v);
7327 return NULL;
7328}
7329
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007330/* Charmap encoding: the lookup table */
7331
Alexander Belopolsky40018472011-02-26 01:02:56 +00007332struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007333 PyObject_HEAD
7334 unsigned char level1[32];
7335 int count2, count3;
7336 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007337};
7338
7339static PyObject*
7340encoding_map_size(PyObject *obj, PyObject* args)
7341{
7342 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007343 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007344 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007345}
7346
7347static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007348 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007349 PyDoc_STR("Return the size (in bytes) of this object") },
7350 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007351};
7352
7353static void
7354encoding_map_dealloc(PyObject* o)
7355{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007356 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007357}
7358
7359static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007360 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007361 "EncodingMap", /*tp_name*/
7362 sizeof(struct encoding_map), /*tp_basicsize*/
7363 0, /*tp_itemsize*/
7364 /* methods */
7365 encoding_map_dealloc, /*tp_dealloc*/
7366 0, /*tp_print*/
7367 0, /*tp_getattr*/
7368 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007369 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 0, /*tp_repr*/
7371 0, /*tp_as_number*/
7372 0, /*tp_as_sequence*/
7373 0, /*tp_as_mapping*/
7374 0, /*tp_hash*/
7375 0, /*tp_call*/
7376 0, /*tp_str*/
7377 0, /*tp_getattro*/
7378 0, /*tp_setattro*/
7379 0, /*tp_as_buffer*/
7380 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7381 0, /*tp_doc*/
7382 0, /*tp_traverse*/
7383 0, /*tp_clear*/
7384 0, /*tp_richcompare*/
7385 0, /*tp_weaklistoffset*/
7386 0, /*tp_iter*/
7387 0, /*tp_iternext*/
7388 encoding_map_methods, /*tp_methods*/
7389 0, /*tp_members*/
7390 0, /*tp_getset*/
7391 0, /*tp_base*/
7392 0, /*tp_dict*/
7393 0, /*tp_descr_get*/
7394 0, /*tp_descr_set*/
7395 0, /*tp_dictoffset*/
7396 0, /*tp_init*/
7397 0, /*tp_alloc*/
7398 0, /*tp_new*/
7399 0, /*tp_free*/
7400 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007401};
7402
7403PyObject*
7404PyUnicode_BuildEncodingMap(PyObject* string)
7405{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007406 PyObject *result;
7407 struct encoding_map *mresult;
7408 int i;
7409 int need_dict = 0;
7410 unsigned char level1[32];
7411 unsigned char level2[512];
7412 unsigned char *mlevel1, *mlevel2, *mlevel3;
7413 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007414 int kind;
7415 void *data;
7416 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007418 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007419 PyErr_BadArgument();
7420 return NULL;
7421 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007422 kind = PyUnicode_KIND(string);
7423 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007424 memset(level1, 0xFF, sizeof level1);
7425 memset(level2, 0xFF, sizeof level2);
7426
7427 /* If there isn't a one-to-one mapping of NULL to \0,
7428 or if there are non-BMP characters, we need to use
7429 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007430 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007431 need_dict = 1;
7432 for (i = 1; i < 256; i++) {
7433 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007434 ch = PyUnicode_READ(kind, data, i);
7435 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007436 need_dict = 1;
7437 break;
7438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007439 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007440 /* unmapped character */
7441 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007442 l1 = ch >> 11;
7443 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007444 if (level1[l1] == 0xFF)
7445 level1[l1] = count2++;
7446 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007447 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007448 }
7449
7450 if (count2 >= 0xFF || count3 >= 0xFF)
7451 need_dict = 1;
7452
7453 if (need_dict) {
7454 PyObject *result = PyDict_New();
7455 PyObject *key, *value;
7456 if (!result)
7457 return NULL;
7458 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007459 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007460 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007461 if (!key || !value)
7462 goto failed1;
7463 if (PyDict_SetItem(result, key, value) == -1)
7464 goto failed1;
7465 Py_DECREF(key);
7466 Py_DECREF(value);
7467 }
7468 return result;
7469 failed1:
7470 Py_XDECREF(key);
7471 Py_XDECREF(value);
7472 Py_DECREF(result);
7473 return NULL;
7474 }
7475
7476 /* Create a three-level trie */
7477 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7478 16*count2 + 128*count3 - 1);
7479 if (!result)
7480 return PyErr_NoMemory();
7481 PyObject_Init(result, &EncodingMapType);
7482 mresult = (struct encoding_map*)result;
7483 mresult->count2 = count2;
7484 mresult->count3 = count3;
7485 mlevel1 = mresult->level1;
7486 mlevel2 = mresult->level23;
7487 mlevel3 = mresult->level23 + 16*count2;
7488 memcpy(mlevel1, level1, 32);
7489 memset(mlevel2, 0xFF, 16*count2);
7490 memset(mlevel3, 0, 128*count3);
7491 count3 = 0;
7492 for (i = 1; i < 256; i++) {
7493 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007494 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007495 /* unmapped character */
7496 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007497 o1 = PyUnicode_READ(kind, data, i)>>11;
7498 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007499 i2 = 16*mlevel1[o1] + o2;
7500 if (mlevel2[i2] == 0xFF)
7501 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007502 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007503 i3 = 128*mlevel2[i2] + o3;
7504 mlevel3[i3] = i;
7505 }
7506 return result;
7507}
7508
7509static int
7510encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7511{
7512 struct encoding_map *map = (struct encoding_map*)mapping;
7513 int l1 = c>>11;
7514 int l2 = (c>>7) & 0xF;
7515 int l3 = c & 0x7F;
7516 int i;
7517
7518#ifdef Py_UNICODE_WIDE
7519 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007520 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007521 }
7522#endif
7523 if (c == 0)
7524 return 0;
7525 /* level 1*/
7526 i = map->level1[l1];
7527 if (i == 0xFF) {
7528 return -1;
7529 }
7530 /* level 2*/
7531 i = map->level23[16*i+l2];
7532 if (i == 0xFF) {
7533 return -1;
7534 }
7535 /* level 3 */
7536 i = map->level23[16*map->count2 + 128*i + l3];
7537 if (i == 0) {
7538 return -1;
7539 }
7540 return i;
7541}
7542
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007543/* Lookup the character ch in the mapping. If the character
7544 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007545 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007546static PyObject *
7547charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007548{
Christian Heimes217cfd12007-12-02 14:31:20 +00007549 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007550 PyObject *x;
7551
7552 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007553 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007554 x = PyObject_GetItem(mapping, w);
7555 Py_DECREF(w);
7556 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007557 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7558 /* No mapping found means: mapping is undefined. */
7559 PyErr_Clear();
7560 x = Py_None;
7561 Py_INCREF(x);
7562 return x;
7563 } else
7564 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007565 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007566 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007568 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 long value = PyLong_AS_LONG(x);
7570 if (value < 0 || value > 255) {
7571 PyErr_SetString(PyExc_TypeError,
7572 "character mapping must be in range(256)");
7573 Py_DECREF(x);
7574 return NULL;
7575 }
7576 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007577 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007578 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007580 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007581 /* wrong return value */
7582 PyErr_Format(PyExc_TypeError,
7583 "character mapping must return integer, bytes or None, not %.400s",
7584 x->ob_type->tp_name);
7585 Py_DECREF(x);
7586 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587 }
7588}
7589
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007590static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007591charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007592{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007593 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7594 /* exponentially overallocate to minimize reallocations */
7595 if (requiredsize < 2*outsize)
7596 requiredsize = 2*outsize;
7597 if (_PyBytes_Resize(outobj, requiredsize))
7598 return -1;
7599 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007600}
7601
Benjamin Peterson14339b62009-01-31 16:36:08 +00007602typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007604} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007605/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007606 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007607 space is available. Return a new reference to the object that
7608 was put in the output buffer, or Py_None, if the mapping was undefined
7609 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007610 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007611static charmapencode_result
7612charmapencode_output(Py_UNICODE c, PyObject *mapping,
7613 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007614{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007615 PyObject *rep;
7616 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007617 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007618
Christian Heimes90aa7642007-12-19 02:45:37 +00007619 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007620 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007622 if (res == -1)
7623 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007624 if (outsize<requiredsize)
7625 if (charmapencode_resize(outobj, outpos, requiredsize))
7626 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007627 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007628 outstart[(*outpos)++] = (char)res;
7629 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007630 }
7631
7632 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007633 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007635 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 Py_DECREF(rep);
7637 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007638 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007639 if (PyLong_Check(rep)) {
7640 Py_ssize_t requiredsize = *outpos+1;
7641 if (outsize<requiredsize)
7642 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7643 Py_DECREF(rep);
7644 return enc_EXCEPTION;
7645 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007646 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007648 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 else {
7650 const char *repchars = PyBytes_AS_STRING(rep);
7651 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
7652 Py_ssize_t requiredsize = *outpos+repsize;
7653 if (outsize<requiredsize)
7654 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7655 Py_DECREF(rep);
7656 return enc_EXCEPTION;
7657 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007658 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 memcpy(outstart + *outpos, repchars, repsize);
7660 *outpos += repsize;
7661 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007662 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007663 Py_DECREF(rep);
7664 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007665}
7666
7667/* handle an error in PyUnicode_EncodeCharmap
7668 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007669static int
7670charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00007671 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007672 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00007673 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00007674 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007675{
7676 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007677 Py_ssize_t repsize;
7678 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007679 Py_UNICODE *uni2;
7680 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007681 Py_ssize_t collstartpos = *inpos;
7682 Py_ssize_t collendpos = *inpos+1;
7683 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007684 char *encoding = "charmap";
7685 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007686 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007687
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007688 /* find all unencodable characters */
7689 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007690 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00007691 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 int res = encoding_map_lookup(p[collendpos], mapping);
7693 if (res != -1)
7694 break;
7695 ++collendpos;
7696 continue;
7697 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007698
Benjamin Peterson29060642009-01-31 22:14:21 +00007699 rep = charmapencode_lookup(p[collendpos], mapping);
7700 if (rep==NULL)
7701 return -1;
7702 else if (rep!=Py_None) {
7703 Py_DECREF(rep);
7704 break;
7705 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007706 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007708 }
7709 /* cache callback name lookup
7710 * (if not done yet, i.e. it's the first error) */
7711 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007712 if ((errors==NULL) || (!strcmp(errors, "strict")))
7713 *known_errorHandler = 1;
7714 else if (!strcmp(errors, "replace"))
7715 *known_errorHandler = 2;
7716 else if (!strcmp(errors, "ignore"))
7717 *known_errorHandler = 3;
7718 else if (!strcmp(errors, "xmlcharrefreplace"))
7719 *known_errorHandler = 4;
7720 else
7721 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007722 }
7723 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007724 case 1: /* strict */
7725 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7726 return -1;
7727 case 2: /* replace */
7728 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 x = charmapencode_output('?', mapping, res, respos);
7730 if (x==enc_EXCEPTION) {
7731 return -1;
7732 }
7733 else if (x==enc_FAILED) {
7734 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7735 return -1;
7736 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007737 }
7738 /* fall through */
7739 case 3: /* ignore */
7740 *inpos = collendpos;
7741 break;
7742 case 4: /* xmlcharrefreplace */
7743 /* generate replacement (temporarily (mis)uses p) */
7744 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 char buffer[2+29+1+1];
7746 char *cp;
7747 sprintf(buffer, "&#%d;", (int)p[collpos]);
7748 for (cp = buffer; *cp; ++cp) {
7749 x = charmapencode_output(*cp, mapping, res, respos);
7750 if (x==enc_EXCEPTION)
7751 return -1;
7752 else if (x==enc_FAILED) {
7753 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7754 return -1;
7755 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007756 }
7757 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007758 *inpos = collendpos;
7759 break;
7760 default:
7761 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00007762 encoding, reason, p, size, exceptionObject,
7763 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007764 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007765 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00007766 if (PyBytes_Check(repunicode)) {
7767 /* Directly copy bytes result to output. */
7768 Py_ssize_t outsize = PyBytes_Size(*res);
7769 Py_ssize_t requiredsize;
7770 repsize = PyBytes_Size(repunicode);
7771 requiredsize = *respos + repsize;
7772 if (requiredsize > outsize)
7773 /* Make room for all additional bytes. */
7774 if (charmapencode_resize(res, respos, requiredsize)) {
7775 Py_DECREF(repunicode);
7776 return -1;
7777 }
7778 memcpy(PyBytes_AsString(*res) + *respos,
7779 PyBytes_AsString(repunicode), repsize);
7780 *respos += repsize;
7781 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007782 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00007783 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007784 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007785 /* generate replacement */
7786 repsize = PyUnicode_GET_SIZE(repunicode);
7787 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007788 x = charmapencode_output(*uni2, mapping, res, respos);
7789 if (x==enc_EXCEPTION) {
7790 return -1;
7791 }
7792 else if (x==enc_FAILED) {
7793 Py_DECREF(repunicode);
7794 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
7795 return -1;
7796 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797 }
7798 *inpos = newpos;
7799 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007800 }
7801 return 0;
7802}
7803
Alexander Belopolsky40018472011-02-26 01:02:56 +00007804PyObject *
7805PyUnicode_EncodeCharmap(const Py_UNICODE *p,
7806 Py_ssize_t size,
7807 PyObject *mapping,
7808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007810 /* output object */
7811 PyObject *res = NULL;
7812 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007813 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007814 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00007815 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007816 PyObject *errorHandler = NULL;
7817 PyObject *exc = NULL;
7818 /* the following variable is used for caching string comparisons
7819 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
7820 * 3=ignore, 4=xmlcharrefreplace */
7821 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007822
7823 /* Default to Latin-1 */
7824 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007825 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007827 /* allocate enough for a simple encoding without
7828 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00007829 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007830 if (res == NULL)
7831 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00007832 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007835 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 /* try to encode it */
7837 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
7838 if (x==enc_EXCEPTION) /* error */
7839 goto onError;
7840 if (x==enc_FAILED) { /* unencodable character */
7841 if (charmap_encoding_error(p, size, &inpos, mapping,
7842 &exc,
7843 &known_errorHandler, &errorHandler, errors,
7844 &res, &respos)) {
7845 goto onError;
7846 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007847 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 else
7849 /* done with this character => adjust input position */
7850 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007853 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00007854 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007855 if (_PyBytes_Resize(&res, respos) < 0)
7856 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00007857
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007858 Py_XDECREF(exc);
7859 Py_XDECREF(errorHandler);
7860 return res;
7861
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007863 Py_XDECREF(res);
7864 Py_XDECREF(exc);
7865 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007866 return NULL;
7867}
7868
Alexander Belopolsky40018472011-02-26 01:02:56 +00007869PyObject *
7870PyUnicode_AsCharmapString(PyObject *unicode,
7871 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007872{
7873 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 PyErr_BadArgument();
7875 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007876 }
7877 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 PyUnicode_GET_SIZE(unicode),
7879 mapping,
7880 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007881}
7882
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007883/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007884static void
7885make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007887 Py_ssize_t startpos, Py_ssize_t endpos,
7888 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007889{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007890 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007891 *exceptionObject = _PyUnicodeTranslateError_Create(
7892 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007893 }
7894 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
7896 goto onError;
7897 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
7898 goto onError;
7899 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
7900 goto onError;
7901 return;
7902 onError:
7903 Py_DECREF(*exceptionObject);
7904 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007905 }
7906}
7907
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007908/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007909static void
7910raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007911 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007912 Py_ssize_t startpos, Py_ssize_t endpos,
7913 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007914{
7915 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007916 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007918 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919}
7920
7921/* error handling callback helper:
7922 build arguments, call the callback and check the arguments,
7923 put the result into newpos and return the replacement string, which
7924 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925static PyObject *
7926unicode_translate_call_errorhandler(const char *errors,
7927 PyObject **errorHandler,
7928 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007929 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00007930 Py_ssize_t startpos, Py_ssize_t endpos,
7931 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007932{
Benjamin Peterson142957c2008-07-04 19:55:29 +00007933 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007934
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007935 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007936 PyObject *restuple;
7937 PyObject *resunicode;
7938
7939 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007943 }
7944
7945 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007947 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007949
7950 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007952 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007953 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007954 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00007955 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 Py_DECREF(restuple);
7957 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007958 }
7959 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 &resunicode, &i_newpos)) {
7961 Py_DECREF(restuple);
7962 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007963 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00007964 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007965 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007966 else
7967 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007968 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007969 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
7970 Py_DECREF(restuple);
7971 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00007972 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007973 Py_INCREF(resunicode);
7974 Py_DECREF(restuple);
7975 return resunicode;
7976}
7977
7978/* Lookup the character ch in the mapping and put the result in result,
7979 which must be decrefed by the caller.
7980 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007982charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983{
Christian Heimes217cfd12007-12-02 14:31:20 +00007984 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 PyObject *x;
7986
7987 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007989 x = PyObject_GetItem(mapping, w);
7990 Py_DECREF(w);
7991 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7993 /* No mapping found means: use 1:1 mapping. */
7994 PyErr_Clear();
7995 *result = NULL;
7996 return 0;
7997 } else
7998 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007999 }
8000 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008001 *result = x;
8002 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008003 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008004 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 long value = PyLong_AS_LONG(x);
8006 long max = PyUnicode_GetMax();
8007 if (value < 0 || value > max) {
8008 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008009 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 Py_DECREF(x);
8011 return -1;
8012 }
8013 *result = x;
8014 return 0;
8015 }
8016 else if (PyUnicode_Check(x)) {
8017 *result = x;
8018 return 0;
8019 }
8020 else {
8021 /* wrong return value */
8022 PyErr_SetString(PyExc_TypeError,
8023 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008024 Py_DECREF(x);
8025 return -1;
8026 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008027}
8028/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 if not reallocate and adjust various state variables.
8030 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008031static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008036 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 /* exponentially overallocate to minimize reallocations */
8038 if (requiredsize < 2 * oldsize)
8039 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008040 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8041 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008043 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008044 }
8045 return 0;
8046}
8047/* lookup the character, put the result in the output string and adjust
8048 various state variables. Return a new reference to the object that
8049 was put in the output buffer in *result, or Py_None, if the mapping was
8050 undefined (in which case no character was written).
8051 The called must decref result.
8052 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008053static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008054charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8055 PyObject *mapping, Py_UCS4 **output,
8056 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008057 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008059 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8060 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008064 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065 }
8066 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008068 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008070 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071 }
8072 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008073 Py_ssize_t repsize;
8074 if (PyUnicode_READY(*res) == -1)
8075 return -1;
8076 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 if (repsize==1) {
8078 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008079 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 }
8081 else if (repsize!=0) {
8082 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008083 Py_ssize_t requiredsize = *opos +
8084 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 Py_ssize_t i;
8087 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008088 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 for(i = 0; i < repsize; i++)
8090 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 }
8093 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008095 return 0;
8096}
8097
Alexander Belopolsky40018472011-02-26 01:02:56 +00008098PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008099_PyUnicode_TranslateCharmap(PyObject *input,
8100 PyObject *mapping,
8101 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 /* input object */
8104 char *idata;
8105 Py_ssize_t size, i;
8106 int kind;
8107 /* output buffer */
8108 Py_UCS4 *output = NULL;
8109 Py_ssize_t osize;
8110 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008111 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008112 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113 char *reason = "character maps to <undefined>";
8114 PyObject *errorHandler = NULL;
8115 PyObject *exc = NULL;
8116 /* the following variable is used for caching string comparisons
8117 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8118 * 3=ignore, 4=xmlcharrefreplace */
8119 int known_errorHandler = -1;
8120
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 PyErr_BadArgument();
8123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008124 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008126 if (PyUnicode_READY(input) == -1)
8127 return NULL;
8128 idata = (char*)PyUnicode_DATA(input);
8129 kind = PyUnicode_KIND(input);
8130 size = PyUnicode_GET_LENGTH(input);
8131 i = 0;
8132
8133 if (size == 0) {
8134 Py_INCREF(input);
8135 return input;
8136 }
8137
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008138 /* allocate enough for a simple 1:1 translation without
8139 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008140 osize = size;
8141 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8142 opos = 0;
8143 if (output == NULL) {
8144 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008146 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008148 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 /* try to encode it */
8150 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008151 if (charmaptranslate_output(input, i, mapping,
8152 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 Py_XDECREF(x);
8154 goto onError;
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008158 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 else { /* untranslatable character */
8160 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8161 Py_ssize_t repsize;
8162 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008163 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008165 Py_ssize_t collstart = i;
8166 Py_ssize_t collend = i+1;
8167 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008168
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008170 while (collend < size) {
8171 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 goto onError;
8173 Py_XDECREF(x);
8174 if (x!=Py_None)
8175 break;
8176 ++collend;
8177 }
8178 /* cache callback name lookup
8179 * (if not done yet, i.e. it's the first error) */
8180 if (known_errorHandler==-1) {
8181 if ((errors==NULL) || (!strcmp(errors, "strict")))
8182 known_errorHandler = 1;
8183 else if (!strcmp(errors, "replace"))
8184 known_errorHandler = 2;
8185 else if (!strcmp(errors, "ignore"))
8186 known_errorHandler = 3;
8187 else if (!strcmp(errors, "xmlcharrefreplace"))
8188 known_errorHandler = 4;
8189 else
8190 known_errorHandler = 0;
8191 }
8192 switch (known_errorHandler) {
8193 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008194 raise_translate_exception(&exc, input, collstart,
8195 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008196 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 case 2: /* replace */
8198 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008199 for (coll = collstart; coll<collend; coll++)
8200 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008201 /* fall through */
8202 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008203 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 break;
8205 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008206 /* generate replacement (temporarily (mis)uses i) */
8207 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 char buffer[2+29+1+1];
8209 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008210 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8211 if (charmaptranslate_makespace(&output, &osize,
8212 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 goto onError;
8214 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008215 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008217 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 break;
8219 default:
8220 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008221 reason, input, &exc,
8222 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008223 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 goto onError;
8225 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008226 repsize = PyUnicode_GET_LENGTH(repunicode);
8227 if (charmaptranslate_makespace(&output, &osize,
8228 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 Py_DECREF(repunicode);
8230 goto onError;
8231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008232 for (uni2 = 0; repsize-->0; ++uni2)
8233 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8234 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008236 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 }
8238 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008239 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8240 if (!res)
8241 goto onError;
8242 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 Py_XDECREF(exc);
8244 Py_XDECREF(errorHandler);
8245 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008248 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008249 Py_XDECREF(exc);
8250 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 return NULL;
8252}
8253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008254/* Deprecated. Use PyUnicode_Translate instead. */
8255PyObject *
8256PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8257 Py_ssize_t size,
8258 PyObject *mapping,
8259 const char *errors)
8260{
8261 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8262 if (!unicode)
8263 return NULL;
8264 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8265}
8266
Alexander Belopolsky40018472011-02-26 01:02:56 +00008267PyObject *
8268PyUnicode_Translate(PyObject *str,
8269 PyObject *mapping,
8270 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008271{
8272 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008273
Guido van Rossumd57fd912000-03-10 22:53:23 +00008274 str = PyUnicode_FromObject(str);
8275 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008277 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 Py_DECREF(str);
8279 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008280
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282 Py_XDECREF(str);
8283 return NULL;
8284}
Tim Petersced69f82003-09-16 20:30:58 +00008285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008287fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008288{
8289 /* No need to call PyUnicode_READY(self) because this function is only
8290 called as a callback from fixup() which does it already. */
8291 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8292 const int kind = PyUnicode_KIND(self);
8293 void *data = PyUnicode_DATA(self);
8294 Py_UCS4 maxchar = 0, ch, fixed;
8295 Py_ssize_t i;
8296
8297 for (i = 0; i < len; ++i) {
8298 ch = PyUnicode_READ(kind, data, i);
8299 fixed = 0;
8300 if (ch > 127) {
8301 if (Py_UNICODE_ISSPACE(ch))
8302 fixed = ' ';
8303 else {
8304 const int decimal = Py_UNICODE_TODECIMAL(ch);
8305 if (decimal >= 0)
8306 fixed = '0' + decimal;
8307 }
8308 if (fixed != 0) {
8309 if (fixed > maxchar)
8310 maxchar = fixed;
8311 PyUnicode_WRITE(kind, data, i, fixed);
8312 }
8313 else if (ch > maxchar)
8314 maxchar = ch;
8315 }
8316 else if (ch > maxchar)
8317 maxchar = ch;
8318 }
8319
8320 return maxchar;
8321}
8322
8323PyObject *
8324_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8325{
8326 if (!PyUnicode_Check(unicode)) {
8327 PyErr_BadInternalCall();
8328 return NULL;
8329 }
8330 if (PyUnicode_READY(unicode) == -1)
8331 return NULL;
8332 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8333 /* If the string is already ASCII, just return the same string */
8334 Py_INCREF(unicode);
8335 return unicode;
8336 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008337 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008338}
8339
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008340PyObject *
8341PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8342 Py_ssize_t length)
8343{
8344 PyObject *result;
8345 Py_UNICODE *p; /* write pointer into result */
8346 Py_ssize_t i;
8347 /* Copy to a new string */
8348 result = (PyObject *)_PyUnicode_New(length);
8349 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8350 if (result == NULL)
8351 return result;
8352 p = PyUnicode_AS_UNICODE(result);
8353 /* Iterate over code points */
8354 for (i = 0; i < length; i++) {
8355 Py_UNICODE ch =s[i];
8356 if (ch > 127) {
8357 int decimal = Py_UNICODE_TODECIMAL(ch);
8358 if (decimal >= 0)
8359 p[i] = '0' + decimal;
8360 }
8361 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008362#ifndef DONT_MAKE_RESULT_READY
8363 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 Py_DECREF(result);
8365 return NULL;
8366 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008367#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008368 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008369 return result;
8370}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008371/* --- Decimal Encoder ---------------------------------------------------- */
8372
Alexander Belopolsky40018472011-02-26 01:02:56 +00008373int
8374PyUnicode_EncodeDecimal(Py_UNICODE *s,
8375 Py_ssize_t length,
8376 char *output,
8377 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008378{
8379 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 PyObject *errorHandler = NULL;
8381 PyObject *exc = NULL;
8382 const char *encoding = "decimal";
8383 const char *reason = "invalid decimal Unicode string";
8384 /* the following variable is used for caching string comparisons
8385 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8386 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008387
8388 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 PyErr_BadArgument();
8390 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008391 }
8392
8393 p = s;
8394 end = s + length;
8395 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 register Py_UNICODE ch = *p;
8397 int decimal;
8398 PyObject *repunicode;
8399 Py_ssize_t repsize;
8400 Py_ssize_t newpos;
8401 Py_UNICODE *uni2;
8402 Py_UNICODE *collstart;
8403 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008404
Benjamin Peterson29060642009-01-31 22:14:21 +00008405 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008406 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 ++p;
8408 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 decimal = Py_UNICODE_TODECIMAL(ch);
8411 if (decimal >= 0) {
8412 *output++ = '0' + decimal;
8413 ++p;
8414 continue;
8415 }
8416 if (0 < ch && ch < 256) {
8417 *output++ = (char)ch;
8418 ++p;
8419 continue;
8420 }
8421 /* All other characters are considered unencodable */
8422 collstart = p;
8423 collend = p+1;
8424 while (collend < end) {
8425 if ((0 < *collend && *collend < 256) ||
8426 !Py_UNICODE_ISSPACE(*collend) ||
8427 Py_UNICODE_TODECIMAL(*collend))
8428 break;
8429 }
8430 /* cache callback name lookup
8431 * (if not done yet, i.e. it's the first error) */
8432 if (known_errorHandler==-1) {
8433 if ((errors==NULL) || (!strcmp(errors, "strict")))
8434 known_errorHandler = 1;
8435 else if (!strcmp(errors, "replace"))
8436 known_errorHandler = 2;
8437 else if (!strcmp(errors, "ignore"))
8438 known_errorHandler = 3;
8439 else if (!strcmp(errors, "xmlcharrefreplace"))
8440 known_errorHandler = 4;
8441 else
8442 known_errorHandler = 0;
8443 }
8444 switch (known_errorHandler) {
8445 case 1: /* strict */
8446 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8447 goto onError;
8448 case 2: /* replace */
8449 for (p = collstart; p < collend; ++p)
8450 *output++ = '?';
8451 /* fall through */
8452 case 3: /* ignore */
8453 p = collend;
8454 break;
8455 case 4: /* xmlcharrefreplace */
8456 /* generate replacement (temporarily (mis)uses p) */
8457 for (p = collstart; p < collend; ++p)
8458 output += sprintf(output, "&#%d;", (int)*p);
8459 p = collend;
8460 break;
8461 default:
8462 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8463 encoding, reason, s, length, &exc,
8464 collstart-s, collend-s, &newpos);
8465 if (repunicode == NULL)
8466 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008467 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008468 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008469 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8470 Py_DECREF(repunicode);
8471 goto onError;
8472 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 /* generate replacement */
8474 repsize = PyUnicode_GET_SIZE(repunicode);
8475 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8476 Py_UNICODE ch = *uni2;
8477 if (Py_UNICODE_ISSPACE(ch))
8478 *output++ = ' ';
8479 else {
8480 decimal = Py_UNICODE_TODECIMAL(ch);
8481 if (decimal >= 0)
8482 *output++ = '0' + decimal;
8483 else if (0 < ch && ch < 256)
8484 *output++ = (char)ch;
8485 else {
8486 Py_DECREF(repunicode);
8487 raise_encode_exception(&exc, encoding,
8488 s, length, collstart-s, collend-s, reason);
8489 goto onError;
8490 }
8491 }
8492 }
8493 p = s + newpos;
8494 Py_DECREF(repunicode);
8495 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008496 }
8497 /* 0-terminate the output string */
8498 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 Py_XDECREF(exc);
8500 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008501 return 0;
8502
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 Py_XDECREF(exc);
8505 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008506 return -1;
8507}
8508
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509/* --- Helpers ------------------------------------------------------------ */
8510
Victor Stinnerc3cec782011-10-05 21:24:08 +02008511#include "stringlib/asciilib.h"
8512#include "stringlib/fastsearch.h"
8513#include "stringlib/partition.h"
8514#include "stringlib/split.h"
8515#include "stringlib/count.h"
8516#include "stringlib/find.h"
8517#include "stringlib/localeutil.h"
8518#include "stringlib/undef.h"
8519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520#include "stringlib/ucs1lib.h"
8521#include "stringlib/fastsearch.h"
8522#include "stringlib/partition.h"
8523#include "stringlib/split.h"
8524#include "stringlib/count.h"
8525#include "stringlib/find.h"
8526#include "stringlib/localeutil.h"
8527#include "stringlib/undef.h"
8528
8529#include "stringlib/ucs2lib.h"
8530#include "stringlib/fastsearch.h"
8531#include "stringlib/partition.h"
8532#include "stringlib/split.h"
8533#include "stringlib/count.h"
8534#include "stringlib/find.h"
8535#include "stringlib/localeutil.h"
8536#include "stringlib/undef.h"
8537
8538#include "stringlib/ucs4lib.h"
8539#include "stringlib/fastsearch.h"
8540#include "stringlib/partition.h"
8541#include "stringlib/split.h"
8542#include "stringlib/count.h"
8543#include "stringlib/find.h"
8544#include "stringlib/localeutil.h"
8545#include "stringlib/undef.h"
8546
8547static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008548any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 Py_ssize_t start,
8550 Py_ssize_t end)
8551{
8552 int kind1, kind2, kind;
8553 void *buf1, *buf2;
8554 Py_ssize_t len1, len2, result;
8555
8556 kind1 = PyUnicode_KIND(s1);
8557 kind2 = PyUnicode_KIND(s2);
8558 kind = kind1 > kind2 ? kind1 : kind2;
8559 buf1 = PyUnicode_DATA(s1);
8560 buf2 = PyUnicode_DATA(s2);
8561 if (kind1 != kind)
8562 buf1 = _PyUnicode_AsKind(s1, kind);
8563 if (!buf1)
8564 return -2;
8565 if (kind2 != kind)
8566 buf2 = _PyUnicode_AsKind(s2, kind);
8567 if (!buf2) {
8568 if (kind1 != kind) PyMem_Free(buf1);
8569 return -2;
8570 }
8571 len1 = PyUnicode_GET_LENGTH(s1);
8572 len2 = PyUnicode_GET_LENGTH(s2);
8573
Victor Stinner794d5672011-10-10 03:21:36 +02008574 if (direction > 0) {
8575 switch(kind) {
8576 case PyUnicode_1BYTE_KIND:
8577 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8578 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8579 else
8580 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8581 break;
8582 case PyUnicode_2BYTE_KIND:
8583 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8584 break;
8585 case PyUnicode_4BYTE_KIND:
8586 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8587 break;
8588 default:
8589 assert(0); result = -2;
8590 }
8591 }
8592 else {
8593 switch(kind) {
8594 case PyUnicode_1BYTE_KIND:
8595 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8596 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8597 else
8598 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8599 break;
8600 case PyUnicode_2BYTE_KIND:
8601 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8602 break;
8603 case PyUnicode_4BYTE_KIND:
8604 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8605 break;
8606 default:
8607 assert(0); result = -2;
8608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 }
8610
8611 if (kind1 != kind)
8612 PyMem_Free(buf1);
8613 if (kind2 != kind)
8614 PyMem_Free(buf2);
8615
8616 return result;
8617}
8618
8619Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008620_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621 Py_ssize_t n_buffer,
8622 void *digits, Py_ssize_t n_digits,
8623 Py_ssize_t min_width,
8624 const char *grouping,
8625 const char *thousands_sep)
8626{
8627 switch(kind) {
8628 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008629 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8630 return _PyUnicode_ascii_InsertThousandsGrouping(
8631 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8632 min_width, grouping, thousands_sep);
8633 else
8634 return _PyUnicode_ucs1_InsertThousandsGrouping(
8635 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8636 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 case PyUnicode_2BYTE_KIND:
8638 return _PyUnicode_ucs2_InsertThousandsGrouping(
8639 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8640 min_width, grouping, thousands_sep);
8641 case PyUnicode_4BYTE_KIND:
8642 return _PyUnicode_ucs4_InsertThousandsGrouping(
8643 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8644 min_width, grouping, thousands_sep);
8645 }
8646 assert(0);
8647 return -1;
8648}
8649
8650
Eric Smith8c663262007-08-25 02:26:07 +00008651#include "stringlib/unicodedefs.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00008652#include "stringlib/fastsearch.h"
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008653
Thomas Wouters477c8d52006-05-27 19:21:47 +00008654#include "stringlib/count.h"
8655#include "stringlib/find.h"
Eric Smith5807c412008-05-11 21:00:57 +00008656
Thomas Wouters477c8d52006-05-27 19:21:47 +00008657/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00008658#define ADJUST_INDICES(start, end, len) \
8659 if (end > len) \
8660 end = len; \
8661 else if (end < 0) { \
8662 end += len; \
8663 if (end < 0) \
8664 end = 0; \
8665 } \
8666 if (start < 0) { \
8667 start += len; \
8668 if (start < 0) \
8669 start = 0; \
8670 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008671
Alexander Belopolsky40018472011-02-26 01:02:56 +00008672Py_ssize_t
8673PyUnicode_Count(PyObject *str,
8674 PyObject *substr,
8675 Py_ssize_t start,
8676 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008678 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008679 PyUnicodeObject* str_obj;
8680 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 int kind1, kind2, kind;
8682 void *buf1 = NULL, *buf2 = NULL;
8683 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00008684
Thomas Wouters477c8d52006-05-27 19:21:47 +00008685 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008686 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008688 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02008689 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 Py_DECREF(str_obj);
8691 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008692 }
Tim Petersced69f82003-09-16 20:30:58 +00008693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 kind1 = PyUnicode_KIND(str_obj);
8695 kind2 = PyUnicode_KIND(sub_obj);
8696 kind = kind1 > kind2 ? kind1 : kind2;
8697 buf1 = PyUnicode_DATA(str_obj);
8698 if (kind1 != kind)
8699 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
8700 if (!buf1)
8701 goto onError;
8702 buf2 = PyUnicode_DATA(sub_obj);
8703 if (kind2 != kind)
8704 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
8705 if (!buf2)
8706 goto onError;
8707 len1 = PyUnicode_GET_LENGTH(str_obj);
8708 len2 = PyUnicode_GET_LENGTH(sub_obj);
8709
8710 ADJUST_INDICES(start, end, len1);
8711 switch(kind) {
8712 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008713 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
8714 result = asciilib_count(
8715 ((Py_UCS1*)buf1) + start, end - start,
8716 buf2, len2, PY_SSIZE_T_MAX
8717 );
8718 else
8719 result = ucs1lib_count(
8720 ((Py_UCS1*)buf1) + start, end - start,
8721 buf2, len2, PY_SSIZE_T_MAX
8722 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723 break;
8724 case PyUnicode_2BYTE_KIND:
8725 result = ucs2lib_count(
8726 ((Py_UCS2*)buf1) + start, end - start,
8727 buf2, len2, PY_SSIZE_T_MAX
8728 );
8729 break;
8730 case PyUnicode_4BYTE_KIND:
8731 result = ucs4lib_count(
8732 ((Py_UCS4*)buf1) + start, end - start,
8733 buf2, len2, PY_SSIZE_T_MAX
8734 );
8735 break;
8736 default:
8737 assert(0); result = 0;
8738 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00008739
8740 Py_DECREF(sub_obj);
8741 Py_DECREF(str_obj);
8742
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 if (kind1 != kind)
8744 PyMem_Free(buf1);
8745 if (kind2 != kind)
8746 PyMem_Free(buf2);
8747
Guido van Rossumd57fd912000-03-10 22:53:23 +00008748 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 onError:
8750 Py_DECREF(sub_obj);
8751 Py_DECREF(str_obj);
8752 if (kind1 != kind && buf1)
8753 PyMem_Free(buf1);
8754 if (kind2 != kind && buf2)
8755 PyMem_Free(buf2);
8756 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008757}
8758
Alexander Belopolsky40018472011-02-26 01:02:56 +00008759Py_ssize_t
8760PyUnicode_Find(PyObject *str,
8761 PyObject *sub,
8762 Py_ssize_t start,
8763 Py_ssize_t end,
8764 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008766 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008767
Guido van Rossumd57fd912000-03-10 22:53:23 +00008768 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00008771 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008773 Py_DECREF(str);
8774 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008775 }
Tim Petersced69f82003-09-16 20:30:58 +00008776
Victor Stinner794d5672011-10-10 03:21:36 +02008777 result = any_find_slice(direction,
8778 str, sub, start, end
8779 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00008780
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00008782 Py_DECREF(sub);
8783
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 return result;
8785}
8786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787Py_ssize_t
8788PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
8789 Py_ssize_t start, Py_ssize_t end,
8790 int direction)
8791{
8792 char *result;
8793 int kind;
8794 if (PyUnicode_READY(str) == -1)
8795 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02008796 if (start < 0 || end < 0) {
8797 PyErr_SetString(PyExc_IndexError, "string index out of range");
8798 return -2;
8799 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 if (end > PyUnicode_GET_LENGTH(str))
8801 end = PyUnicode_GET_LENGTH(str);
8802 kind = PyUnicode_KIND(str);
8803 result = findchar(PyUnicode_1BYTE_DATA(str)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008804 + kind*start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805 kind,
8806 end-start, ch, direction);
8807 if (!result)
8808 return -1;
8809 return (result-(char*)PyUnicode_DATA(str)) >> (kind-1);
8810}
8811
Alexander Belopolsky40018472011-02-26 01:02:56 +00008812static int
8813tailmatch(PyUnicodeObject *self,
8814 PyUnicodeObject *substring,
8815 Py_ssize_t start,
8816 Py_ssize_t end,
8817 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008818{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 int kind_self;
8820 int kind_sub;
8821 void *data_self;
8822 void *data_sub;
8823 Py_ssize_t offset;
8824 Py_ssize_t i;
8825 Py_ssize_t end_sub;
8826
8827 if (PyUnicode_READY(self) == -1 ||
8828 PyUnicode_READY(substring) == -1)
8829 return 0;
8830
8831 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008832 return 1;
8833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008834 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
8835 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008836 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839 kind_self = PyUnicode_KIND(self);
8840 data_self = PyUnicode_DATA(self);
8841 kind_sub = PyUnicode_KIND(substring);
8842 data_sub = PyUnicode_DATA(substring);
8843 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
8844
8845 if (direction > 0)
8846 offset = end;
8847 else
8848 offset = start;
8849
8850 if (PyUnicode_READ(kind_self, data_self, offset) ==
8851 PyUnicode_READ(kind_sub, data_sub, 0) &&
8852 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
8853 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
8854 /* If both are of the same kind, memcmp is sufficient */
8855 if (kind_self == kind_sub) {
8856 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008857 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008858 data_sub,
8859 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008860 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 }
8862 /* otherwise we have to compare each character by first accesing it */
8863 else {
8864 /* We do not need to compare 0 and len(substring)-1 because
8865 the if statement above ensured already that they are equal
8866 when we end up here. */
8867 // TODO: honor direction and do a forward or backwards search
8868 for (i = 1; i < end_sub; ++i) {
8869 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
8870 PyUnicode_READ(kind_sub, data_sub, i))
8871 return 0;
8872 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875 }
8876
8877 return 0;
8878}
8879
Alexander Belopolsky40018472011-02-26 01:02:56 +00008880Py_ssize_t
8881PyUnicode_Tailmatch(PyObject *str,
8882 PyObject *substr,
8883 Py_ssize_t start,
8884 Py_ssize_t end,
8885 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008886{
Martin v. Löwis18e16552006-02-15 17:27:45 +00008887 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00008888
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889 str = PyUnicode_FromObject(str);
8890 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008892 substr = PyUnicode_FromObject(substr);
8893 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008894 Py_DECREF(str);
8895 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008896 }
Tim Petersced69f82003-09-16 20:30:58 +00008897
Guido van Rossumd57fd912000-03-10 22:53:23 +00008898 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 (PyUnicodeObject *)substr,
8900 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901 Py_DECREF(str);
8902 Py_DECREF(substr);
8903 return result;
8904}
8905
Guido van Rossumd57fd912000-03-10 22:53:23 +00008906/* Apply fixfct filter to the Unicode object self and return a
8907 reference to the modified object */
8908
Alexander Belopolsky40018472011-02-26 01:02:56 +00008909static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02008910fixup(PyObject *self,
8911 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00008912{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008913 PyObject *u;
8914 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916 if (PyUnicode_READY(self) == -1)
8917 return NULL;
8918 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
8919 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
8920 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008921 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02008925 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00008926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 /* fix functions return the new maximum character in a string,
8928 if the kind of the resulting unicode object does not change,
8929 everything is fine. Otherwise we need to change the string kind
8930 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02008931 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 if (maxchar_new == 0)
8933 /* do nothing, keep maxchar_new at 0 which means no changes. */;
8934 else if (maxchar_new <= 127)
8935 maxchar_new = 127;
8936 else if (maxchar_new <= 255)
8937 maxchar_new = 255;
8938 else if (maxchar_new <= 65535)
8939 maxchar_new = 65535;
8940 else
8941 maxchar_new = 1114111; /* 0x10ffff */
8942
8943 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 /* fixfct should return TRUE if it modified the buffer. If
8945 FALSE, return a reference to the original buffer instead
8946 (to save space, not time) */
8947 Py_INCREF(self);
8948 Py_DECREF(u);
8949 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 else if (maxchar_new == maxchar_old) {
8952 return u;
8953 }
8954 else {
8955 /* In case the maximum character changed, we need to
8956 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008957 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 if (v == NULL) {
8959 Py_DECREF(u);
8960 return NULL;
8961 }
8962 if (maxchar_new > maxchar_old) {
8963 /* If the maxchar increased so that the kind changed, not all
8964 characters are representable anymore and we need to fix the
8965 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008966 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02008967 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008968 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
8969 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008970 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02008971 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02008972 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973
8974 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008975 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008976 return v;
8977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978}
8979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008981fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008982{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 /* No need to call PyUnicode_READY(self) because this function is only
8984 called as a callback from fixup() which does it already. */
8985 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8986 const int kind = PyUnicode_KIND(self);
8987 void *data = PyUnicode_DATA(self);
8988 int touched = 0;
8989 Py_UCS4 maxchar = 0;
8990 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00008991
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008992 for (i = 0; i < len; ++i) {
8993 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8994 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
8995 if (up != ch) {
8996 if (up > maxchar)
8997 maxchar = up;
8998 PyUnicode_WRITE(kind, data, i, up);
8999 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009000 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001 else if (ch > maxchar)
9002 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009003 }
9004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009005 if (touched)
9006 return maxchar;
9007 else
9008 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009009}
9010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009012fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9015 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9016 const int kind = PyUnicode_KIND(self);
9017 void *data = PyUnicode_DATA(self);
9018 int touched = 0;
9019 Py_UCS4 maxchar = 0;
9020 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009022 for(i = 0; i < len; ++i) {
9023 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9024 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9025 if (lo != ch) {
9026 if (lo > maxchar)
9027 maxchar = lo;
9028 PyUnicode_WRITE(kind, data, i, lo);
9029 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009031 else if (ch > maxchar)
9032 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009033 }
9034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 if (touched)
9036 return maxchar;
9037 else
9038 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009039}
9040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009042fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009043{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009044 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9045 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9046 const int kind = PyUnicode_KIND(self);
9047 void *data = PyUnicode_DATA(self);
9048 int touched = 0;
9049 Py_UCS4 maxchar = 0;
9050 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052 for(i = 0; i < len; ++i) {
9053 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9054 Py_UCS4 nu = 0;
9055
9056 if (Py_UNICODE_ISUPPER(ch))
9057 nu = Py_UNICODE_TOLOWER(ch);
9058 else if (Py_UNICODE_ISLOWER(ch))
9059 nu = Py_UNICODE_TOUPPER(ch);
9060
9061 if (nu != 0) {
9062 if (nu > maxchar)
9063 maxchar = nu;
9064 PyUnicode_WRITE(kind, data, i, nu);
9065 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009067 else if (ch > maxchar)
9068 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069 }
9070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071 if (touched)
9072 return maxchar;
9073 else
9074 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009075}
9076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009078fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009080 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9081 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9082 const int kind = PyUnicode_KIND(self);
9083 void *data = PyUnicode_DATA(self);
9084 int touched = 0;
9085 Py_UCS4 maxchar = 0;
9086 Py_ssize_t i = 0;
9087 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009088
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009089 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009090 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091
9092 ch = PyUnicode_READ(kind, data, i);
9093 if (!Py_UNICODE_ISUPPER(ch)) {
9094 maxchar = Py_UNICODE_TOUPPER(ch);
9095 PyUnicode_WRITE(kind, data, i, maxchar);
9096 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009098 ++i;
9099 for(; i < len; ++i) {
9100 ch = PyUnicode_READ(kind, data, i);
9101 if (!Py_UNICODE_ISLOWER(ch)) {
9102 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9103 if (lo > maxchar)
9104 maxchar = lo;
9105 PyUnicode_WRITE(kind, data, i, lo);
9106 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 else if (ch > maxchar)
9109 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111
9112 if (touched)
9113 return maxchar;
9114 else
9115 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009116}
9117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009119fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9122 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9123 const int kind = PyUnicode_KIND(self);
9124 void *data = PyUnicode_DATA(self);
9125 Py_UCS4 maxchar = 0;
9126 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127 int previous_is_cased;
9128
9129 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 if (len == 1) {
9131 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9132 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9133 if (ti != ch) {
9134 PyUnicode_WRITE(kind, data, i, ti);
9135 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009136 }
9137 else
9138 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009140 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 for(; i < len; ++i) {
9142 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9143 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009144
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 nu = Py_UNICODE_TOTITLE(ch);
9149
9150 if (nu > maxchar)
9151 maxchar = nu;
9152 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009153
Benjamin Peterson29060642009-01-31 22:14:21 +00009154 if (Py_UNICODE_ISLOWER(ch) ||
9155 Py_UNICODE_ISUPPER(ch) ||
9156 Py_UNICODE_ISTITLE(ch))
9157 previous_is_cased = 1;
9158 else
9159 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009160 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162}
9163
Tim Peters8ce9f162004-08-27 01:49:32 +00009164PyObject *
9165PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009166{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009168 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009170 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009171 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9172 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009173 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009175 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009176 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009177 int use_memcpy;
9178 unsigned char *res_data = NULL, *sep_data = NULL;
9179 PyObject *last_obj;
9180 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181
Tim Peters05eba1f2004-08-27 21:32:02 +00009182 fseq = PySequence_Fast(seq, "");
9183 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009184 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009185 }
9186
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009187 /* NOTE: the following code can't call back into Python code,
9188 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009189 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009190
Tim Peters05eba1f2004-08-27 21:32:02 +00009191 seqlen = PySequence_Fast_GET_SIZE(fseq);
9192 /* If empty sequence, return u"". */
9193 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009194 Py_DECREF(fseq);
9195 Py_INCREF(unicode_empty);
9196 res = unicode_empty;
9197 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009198 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009199
Tim Peters05eba1f2004-08-27 21:32:02 +00009200 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009201 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009202 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009203 if (seqlen == 1) {
9204 if (PyUnicode_CheckExact(items[0])) {
9205 res = items[0];
9206 Py_INCREF(res);
9207 Py_DECREF(fseq);
9208 return res;
9209 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009210 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009211 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009212 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009213 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009214 /* Set up sep and seplen */
9215 if (separator == NULL) {
9216 /* fall back to a blank space separator */
9217 sep = PyUnicode_FromOrdinal(' ');
9218 if (!sep)
9219 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009220 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009221 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009222 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009223 else {
9224 if (!PyUnicode_Check(separator)) {
9225 PyErr_Format(PyExc_TypeError,
9226 "separator: expected str instance,"
9227 " %.80s found",
9228 Py_TYPE(separator)->tp_name);
9229 goto onError;
9230 }
9231 if (PyUnicode_READY(separator))
9232 goto onError;
9233 sep = separator;
9234 seplen = PyUnicode_GET_LENGTH(separator);
9235 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9236 /* inc refcount to keep this code path symmetric with the
9237 above case of a blank separator */
9238 Py_INCREF(sep);
9239 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009240 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009241 }
9242
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009243 /* There are at least two things to join, or else we have a subclass
9244 * of str in the sequence.
9245 * Do a pre-pass to figure out the total amount of space we'll
9246 * need (sz), and see whether all argument are strings.
9247 */
9248 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009249#ifdef Py_DEBUG
9250 use_memcpy = 0;
9251#else
9252 use_memcpy = 1;
9253#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009254 for (i = 0; i < seqlen; i++) {
9255 const Py_ssize_t old_sz = sz;
9256 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009257 if (!PyUnicode_Check(item)) {
9258 PyErr_Format(PyExc_TypeError,
9259 "sequence item %zd: expected str instance,"
9260 " %.80s found",
9261 i, Py_TYPE(item)->tp_name);
9262 goto onError;
9263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 if (PyUnicode_READY(item) == -1)
9265 goto onError;
9266 sz += PyUnicode_GET_LENGTH(item);
9267 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009268 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009269 if (i != 0)
9270 sz += seplen;
9271 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9272 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009273 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009274 goto onError;
9275 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009276 if (use_memcpy && last_obj != NULL) {
9277 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9278 use_memcpy = 0;
9279 }
9280 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009281 }
Tim Petersced69f82003-09-16 20:30:58 +00009282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009284 if (res == NULL)
9285 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009286
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009287 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009288#ifdef Py_DEBUG
9289 use_memcpy = 0;
9290#else
9291 if (use_memcpy) {
9292 res_data = PyUnicode_1BYTE_DATA(res);
9293 kind = PyUnicode_KIND(res);
9294 if (seplen != 0)
9295 sep_data = PyUnicode_1BYTE_DATA(sep);
9296 }
9297#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009299 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009300 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009301 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009302 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009303 if (use_memcpy) {
9304 Py_MEMCPY(res_data,
9305 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009306 kind * seplen);
9307 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009308 }
9309 else {
9310 copy_characters(res, res_offset, sep, 0, seplen);
9311 res_offset += seplen;
9312 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009313 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009314 itemlen = PyUnicode_GET_LENGTH(item);
9315 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009316 if (use_memcpy) {
9317 Py_MEMCPY(res_data,
9318 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009319 kind * itemlen);
9320 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009321 }
9322 else {
9323 copy_characters(res, res_offset, item, 0, itemlen);
9324 res_offset += itemlen;
9325 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009326 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009327 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009328 if (use_memcpy)
9329 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009330 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009331 else
9332 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009333
Tim Peters05eba1f2004-08-27 21:32:02 +00009334 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009336 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009340 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009342 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009343 return NULL;
9344}
9345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346#define FILL(kind, data, value, start, length) \
9347 do { \
9348 Py_ssize_t i_ = 0; \
9349 assert(kind != PyUnicode_WCHAR_KIND); \
9350 switch ((kind)) { \
9351 case PyUnicode_1BYTE_KIND: { \
9352 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9353 memset(to_, (unsigned char)value, length); \
9354 break; \
9355 } \
9356 case PyUnicode_2BYTE_KIND: { \
9357 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9358 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9359 break; \
9360 } \
9361 default: { \
9362 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9363 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9364 break; \
9365 } \
9366 } \
9367 } while (0)
9368
Victor Stinner9310abb2011-10-05 00:59:23 +02009369static PyObject *
9370pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009371 Py_ssize_t left,
9372 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 PyObject *u;
9376 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009377 int kind;
9378 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379
9380 if (left < 0)
9381 left = 0;
9382 if (right < 0)
9383 right = 0;
9384
Tim Peters7a29bd52001-09-12 03:03:31 +00009385 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 Py_INCREF(self);
9387 return self;
9388 }
9389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9391 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009392 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9393 return NULL;
9394 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9396 if (fill > maxchar)
9397 maxchar = fill;
9398 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009399 if (!u)
9400 return NULL;
9401
9402 kind = PyUnicode_KIND(u);
9403 data = PyUnicode_DATA(u);
9404 if (left)
9405 FILL(kind, data, fill, 0, left);
9406 if (right)
9407 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009408 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009409 assert(_PyUnicode_CheckConsistency(u, 1));
9410 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009412#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413
Alexander Belopolsky40018472011-02-26 01:02:56 +00009414PyObject *
9415PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418
9419 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009421 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 switch(PyUnicode_KIND(string)) {
9424 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009425 if (PyUnicode_IS_ASCII(string))
9426 list = asciilib_splitlines(
9427 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9428 PyUnicode_GET_LENGTH(string), keepends);
9429 else
9430 list = ucs1lib_splitlines(
9431 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9432 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009433 break;
9434 case PyUnicode_2BYTE_KIND:
9435 list = ucs2lib_splitlines(
9436 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9437 PyUnicode_GET_LENGTH(string), keepends);
9438 break;
9439 case PyUnicode_4BYTE_KIND:
9440 list = ucs4lib_splitlines(
9441 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9442 PyUnicode_GET_LENGTH(string), keepends);
9443 break;
9444 default:
9445 assert(0);
9446 list = 0;
9447 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009448 Py_DECREF(string);
9449 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450}
9451
Alexander Belopolsky40018472011-02-26 01:02:56 +00009452static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009453split(PyObject *self,
9454 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009455 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 int kind1, kind2, kind;
9458 void *buf1, *buf2;
9459 Py_ssize_t len1, len2;
9460 PyObject* out;
9461
Guido van Rossumd57fd912000-03-10 22:53:23 +00009462 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009463 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 if (PyUnicode_READY(self) == -1)
9466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 if (substring == NULL)
9469 switch(PyUnicode_KIND(self)) {
9470 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009471 if (PyUnicode_IS_ASCII(self))
9472 return asciilib_split_whitespace(
9473 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9474 PyUnicode_GET_LENGTH(self), maxcount
9475 );
9476 else
9477 return ucs1lib_split_whitespace(
9478 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9479 PyUnicode_GET_LENGTH(self), maxcount
9480 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 case PyUnicode_2BYTE_KIND:
9482 return ucs2lib_split_whitespace(
9483 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9484 PyUnicode_GET_LENGTH(self), maxcount
9485 );
9486 case PyUnicode_4BYTE_KIND:
9487 return ucs4lib_split_whitespace(
9488 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9489 PyUnicode_GET_LENGTH(self), maxcount
9490 );
9491 default:
9492 assert(0);
9493 return NULL;
9494 }
9495
9496 if (PyUnicode_READY(substring) == -1)
9497 return NULL;
9498
9499 kind1 = PyUnicode_KIND(self);
9500 kind2 = PyUnicode_KIND(substring);
9501 kind = kind1 > kind2 ? kind1 : kind2;
9502 buf1 = PyUnicode_DATA(self);
9503 buf2 = PyUnicode_DATA(substring);
9504 if (kind1 != kind)
9505 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9506 if (!buf1)
9507 return NULL;
9508 if (kind2 != kind)
9509 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9510 if (!buf2) {
9511 if (kind1 != kind) PyMem_Free(buf1);
9512 return NULL;
9513 }
9514 len1 = PyUnicode_GET_LENGTH(self);
9515 len2 = PyUnicode_GET_LENGTH(substring);
9516
9517 switch(kind) {
9518 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009519 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9520 out = asciilib_split(
9521 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9522 else
9523 out = ucs1lib_split(
9524 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 break;
9526 case PyUnicode_2BYTE_KIND:
9527 out = ucs2lib_split(
9528 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9529 break;
9530 case PyUnicode_4BYTE_KIND:
9531 out = ucs4lib_split(
9532 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9533 break;
9534 default:
9535 out = NULL;
9536 }
9537 if (kind1 != kind)
9538 PyMem_Free(buf1);
9539 if (kind2 != kind)
9540 PyMem_Free(buf2);
9541 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542}
9543
Alexander Belopolsky40018472011-02-26 01:02:56 +00009544static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009545rsplit(PyObject *self,
9546 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009547 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009548{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 int kind1, kind2, kind;
9550 void *buf1, *buf2;
9551 Py_ssize_t len1, len2;
9552 PyObject* out;
9553
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009554 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009555 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 if (PyUnicode_READY(self) == -1)
9558 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 if (substring == NULL)
9561 switch(PyUnicode_KIND(self)) {
9562 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009563 if (PyUnicode_IS_ASCII(self))
9564 return asciilib_rsplit_whitespace(
9565 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9566 PyUnicode_GET_LENGTH(self), maxcount
9567 );
9568 else
9569 return ucs1lib_rsplit_whitespace(
9570 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9571 PyUnicode_GET_LENGTH(self), maxcount
9572 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 case PyUnicode_2BYTE_KIND:
9574 return ucs2lib_rsplit_whitespace(
9575 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9576 PyUnicode_GET_LENGTH(self), maxcount
9577 );
9578 case PyUnicode_4BYTE_KIND:
9579 return ucs4lib_rsplit_whitespace(
9580 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9581 PyUnicode_GET_LENGTH(self), maxcount
9582 );
9583 default:
9584 assert(0);
9585 return NULL;
9586 }
9587
9588 if (PyUnicode_READY(substring) == -1)
9589 return NULL;
9590
9591 kind1 = PyUnicode_KIND(self);
9592 kind2 = PyUnicode_KIND(substring);
9593 kind = kind1 > kind2 ? kind1 : kind2;
9594 buf1 = PyUnicode_DATA(self);
9595 buf2 = PyUnicode_DATA(substring);
9596 if (kind1 != kind)
9597 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9598 if (!buf1)
9599 return NULL;
9600 if (kind2 != kind)
9601 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9602 if (!buf2) {
9603 if (kind1 != kind) PyMem_Free(buf1);
9604 return NULL;
9605 }
9606 len1 = PyUnicode_GET_LENGTH(self);
9607 len2 = PyUnicode_GET_LENGTH(substring);
9608
9609 switch(kind) {
9610 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009611 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9612 out = asciilib_rsplit(
9613 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9614 else
9615 out = ucs1lib_rsplit(
9616 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009617 break;
9618 case PyUnicode_2BYTE_KIND:
9619 out = ucs2lib_rsplit(
9620 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9621 break;
9622 case PyUnicode_4BYTE_KIND:
9623 out = ucs4lib_rsplit(
9624 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9625 break;
9626 default:
9627 out = NULL;
9628 }
9629 if (kind1 != kind)
9630 PyMem_Free(buf1);
9631 if (kind2 != kind)
9632 PyMem_Free(buf2);
9633 return out;
9634}
9635
9636static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009637anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9638 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009639{
9640 switch(kind) {
9641 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009642 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9643 return asciilib_find(buf1, len1, buf2, len2, offset);
9644 else
9645 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646 case PyUnicode_2BYTE_KIND:
9647 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9648 case PyUnicode_4BYTE_KIND:
9649 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9650 }
9651 assert(0);
9652 return -1;
9653}
9654
9655static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009656anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
9657 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658{
9659 switch(kind) {
9660 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009661 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
9662 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
9663 else
9664 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 case PyUnicode_2BYTE_KIND:
9666 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
9667 case PyUnicode_4BYTE_KIND:
9668 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
9669 }
9670 assert(0);
9671 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009672}
9673
Alexander Belopolsky40018472011-02-26 01:02:56 +00009674static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675replace(PyObject *self, PyObject *str1,
9676 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 PyObject *u;
9679 char *sbuf = PyUnicode_DATA(self);
9680 char *buf1 = PyUnicode_DATA(str1);
9681 char *buf2 = PyUnicode_DATA(str2);
9682 int srelease = 0, release1 = 0, release2 = 0;
9683 int skind = PyUnicode_KIND(self);
9684 int kind1 = PyUnicode_KIND(str1);
9685 int kind2 = PyUnicode_KIND(str2);
9686 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
9687 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
9688 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689
9690 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009691 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009693 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694
Victor Stinner59de0ee2011-10-07 10:01:28 +02009695 if (str1 == str2)
9696 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 if (skind < kind1)
9698 /* substring too wide to be present */
9699 goto nothing;
9700
9701 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +00009702 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009703 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009705 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009707 /* replace characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009708 Py_UCS4 u1, u2, maxchar;
9709 int mayshrink, rkind;
9710 u1 = PyUnicode_READ_CHAR(str1, 0);
9711 if (!findchar(sbuf, PyUnicode_KIND(self),
9712 slen, u1, 1))
Thomas Wouters477c8d52006-05-27 19:21:47 +00009713 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 u2 = PyUnicode_READ_CHAR(str2, 0);
9715 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9716 /* Replacing u1 with u2 may cause a maxchar reduction in the
9717 result string. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009718 if (u2 > maxchar) {
9719 maxchar = u2;
9720 mayshrink = 0;
9721 }
Victor Stinnerb9275c12011-10-05 14:01:42 +02009722 else
9723 mayshrink = maxchar > 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009724 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009725 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009727 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009728 rkind = PyUnicode_KIND(u);
9729 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
9730 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009731 if (--maxcount < 0)
9732 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009733 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009734 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009735 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +02009736 unicode_adjust_maxchar(&u);
9737 if (u == NULL)
9738 goto error;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009739 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009740 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741 int rkind = skind;
9742 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009743 PyObject *rstr;
9744 Py_UCS4 maxchar;
9745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009746 if (kind1 < rkind) {
9747 /* widen substring */
9748 buf1 = _PyUnicode_AsKind(str1, rkind);
9749 if (!buf1) goto error;
9750 release1 = 1;
9751 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009752 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009753 if (i < 0)
9754 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009755 if (rkind > kind2) {
9756 /* widen replacement */
9757 buf2 = _PyUnicode_AsKind(str2, rkind);
9758 if (!buf2) goto error;
9759 release2 = 1;
9760 }
9761 else if (rkind < kind2) {
9762 /* widen self and buf1 */
9763 rkind = kind2;
9764 if (release1) PyMem_Free(buf1);
9765 sbuf = _PyUnicode_AsKind(self, rkind);
9766 if (!sbuf) goto error;
9767 srelease = 1;
9768 buf1 = _PyUnicode_AsKind(str1, rkind);
9769 if (!buf1) goto error;
9770 release1 = 1;
9771 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009772 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9773 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9774 rstr = PyUnicode_New(slen, maxchar);
9775 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009776 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009777 res = PyUnicode_DATA(rstr);
9778
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009779 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009780 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009781 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009782 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009783 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009785
9786 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +02009787 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009788 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009789 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009790 if (i == -1)
9791 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009792 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009794 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009795 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009796 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797
Victor Stinner25a4b292011-10-06 12:31:55 +02009798 u = rstr;
9799 unicode_adjust_maxchar(&u);
9800 if (!u)
9801 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803 } else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009805 Py_ssize_t n, i, j, ires;
9806 Py_ssize_t product, new_size;
9807 int rkind = skind;
Victor Stinner25a4b292011-10-06 12:31:55 +02009808 PyObject *rstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +02009810 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 if (kind1 < rkind) {
9813 buf1 = _PyUnicode_AsKind(str1, rkind);
9814 if (!buf1) goto error;
9815 release1 = 1;
9816 }
Victor Stinnerc3cec782011-10-05 21:24:08 +02009817 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009818 if (n == 0)
9819 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009820 if (kind2 < rkind) {
9821 buf2 = _PyUnicode_AsKind(str2, rkind);
9822 if (!buf2) goto error;
9823 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 else if (kind2 > rkind) {
9826 rkind = kind2;
9827 sbuf = _PyUnicode_AsKind(self, rkind);
9828 if (!sbuf) goto error;
9829 srelease = 1;
9830 if (release1) PyMem_Free(buf1);
9831 buf1 = _PyUnicode_AsKind(str1, rkind);
9832 if (!buf1) goto error;
9833 release1 = 1;
9834 }
9835 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
9836 PyUnicode_GET_LENGTH(str1))); */
9837 product = n * (len2-len1);
9838 if ((product / (len2-len1)) != n) {
9839 PyErr_SetString(PyExc_OverflowError,
9840 "replace string is too long");
9841 goto error;
9842 }
9843 new_size = slen + product;
9844 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
9845 PyErr_SetString(PyExc_OverflowError,
9846 "replace string is too long");
9847 goto error;
9848 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009849 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9850 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(str2));
9851 rstr = PyUnicode_New(new_size, maxchar);
9852 if (!rstr)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 goto error;
Victor Stinner25a4b292011-10-06 12:31:55 +02009854 res = PyUnicode_DATA(rstr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 ires = i = 0;
9856 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009857 while (n-- > 0) {
9858 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +02009859 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009860 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009861 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009862 if (j == -1)
9863 break;
9864 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00009865 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009866 memcpy(res + rkind * ires,
9867 sbuf + rkind * i,
9868 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009870 }
9871 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009873 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009875 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009878 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009879 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +00009881 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009882 memcpy(res + rkind * ires,
9883 sbuf + rkind * i,
9884 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009885 } else {
9886 /* interleave */
9887 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009888 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009890 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009892 if (--n <= 0)
9893 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009894 memcpy(res + rkind * ires,
9895 sbuf + rkind * i,
9896 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 ires++;
9898 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009899 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009900 memcpy(res + rkind * ires,
9901 sbuf + rkind * i,
9902 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +00009903 }
Victor Stinner25a4b292011-10-06 12:31:55 +02009904 u = rstr;
9905 unicode_adjust_maxchar(&u);
9906 if (u == NULL)
9907 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 if (srelease)
9910 PyMem_FREE(sbuf);
9911 if (release1)
9912 PyMem_FREE(buf1);
9913 if (release2)
9914 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009915 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009917
Benjamin Peterson29060642009-01-31 22:14:21 +00009918 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +00009919 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 if (srelease)
9921 PyMem_FREE(sbuf);
9922 if (release1)
9923 PyMem_FREE(buf1);
9924 if (release2)
9925 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009926 if (PyUnicode_CheckExact(self)) {
9927 Py_INCREF(self);
9928 return (PyObject *) self;
9929 }
Victor Stinner034f6cf2011-09-30 02:26:44 +02009930 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 error:
9932 if (srelease && sbuf)
9933 PyMem_FREE(sbuf);
9934 if (release1 && buf1)
9935 PyMem_FREE(buf1);
9936 if (release2 && buf2)
9937 PyMem_FREE(buf2);
9938 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939}
9940
9941/* --- Unicode Object Methods --------------------------------------------- */
9942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009943PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009944 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009945\n\
9946Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009947characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009948
9949static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009950unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009951{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952 return fixup(self, fixtitle);
9953}
9954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009955PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009956 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957\n\
9958Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +00009959have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960
9961static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +02009962unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009963{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009964 return fixup(self, fixcapitalize);
9965}
9966
9967#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009968PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +00009969 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +00009970\n\
9971Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00009972normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +00009973
9974static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00009975unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009976{
9977 PyObject *list;
9978 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +00009979 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981 /* Split into words */
9982 list = split(self, NULL, -1);
9983 if (!list)
9984 return NULL;
9985
9986 /* Capitalize each word */
9987 for (i = 0; i < PyList_GET_SIZE(list); i++) {
9988 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +00009989 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990 if (item == NULL)
9991 goto onError;
9992 Py_DECREF(PyList_GET_ITEM(list, i));
9993 PyList_SET_ITEM(list, i, item);
9994 }
9995
9996 /* Join the words to form a new string */
9997 item = PyUnicode_Join(NULL, list);
9998
Benjamin Peterson29060642009-01-31 22:14:21 +00009999 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000 Py_DECREF(list);
10001 return (PyObject *)item;
10002}
10003#endif
10004
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010005/* Argument converter. Coerces to a single unicode character */
10006
10007static int
10008convert_uc(PyObject *obj, void *addr)
10009{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010011 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010012
Benjamin Peterson14339b62009-01-31 16:36:08 +000010013 uniobj = PyUnicode_FromObject(obj);
10014 if (uniobj == NULL) {
10015 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010016 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010017 return 0;
10018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010020 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010021 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010022 Py_DECREF(uniobj);
10023 return 0;
10024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010026 Py_DECREF(uniobj);
10027 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010028}
10029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010030PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010031 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010032\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010033Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010034done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010035
10036static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010037unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010038{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010039 Py_ssize_t marg, left;
10040 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 Py_UCS4 fillchar = ' ';
10042
Victor Stinnere9a29352011-10-01 02:14:59 +020010043 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Victor Stinnere9a29352011-10-01 02:14:59 +020010046 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047 return NULL;
10048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010050 Py_INCREF(self);
10051 return (PyObject*) self;
10052 }
10053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055 left = marg / 2 + (marg & width & 1);
10056
Victor Stinner9310abb2011-10-05 00:59:23 +020010057 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010058}
10059
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060/* This function assumes that str1 and str2 are readied by the caller. */
10061
Marc-André Lemburge5034372000-08-08 08:04:29 +000010062static int
10063unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10064{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 int kind1, kind2;
10066 void *data1, *data2;
10067 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 kind1 = PyUnicode_KIND(str1);
10070 kind2 = PyUnicode_KIND(str2);
10071 data1 = PyUnicode_DATA(str1);
10072 data2 = PyUnicode_DATA(str2);
10073 len1 = PyUnicode_GET_LENGTH(str1);
10074 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 for (i = 0; i < len1 && i < len2; ++i) {
10077 Py_UCS4 c1, c2;
10078 c1 = PyUnicode_READ(kind1, data1, i);
10079 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010080
10081 if (c1 != c2)
10082 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010083 }
10084
10085 return (len1 < len2) ? -1 : (len1 != len2);
10086}
10087
Alexander Belopolsky40018472011-02-26 01:02:56 +000010088int
10089PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010090{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10092 if (PyUnicode_READY(left) == -1 ||
10093 PyUnicode_READY(right) == -1)
10094 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010095 return unicode_compare((PyUnicodeObject *)left,
10096 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010098 PyErr_Format(PyExc_TypeError,
10099 "Can't compare %.100s and %.100s",
10100 left->ob_type->tp_name,
10101 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010102 return -1;
10103}
10104
Martin v. Löwis5b222132007-06-10 09:51:05 +000010105int
10106PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10107{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 Py_ssize_t i;
10109 int kind;
10110 void *data;
10111 Py_UCS4 chr;
10112
Victor Stinner910337b2011-10-03 03:20:16 +020010113 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 if (PyUnicode_READY(uni) == -1)
10115 return -1;
10116 kind = PyUnicode_KIND(uni);
10117 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010118 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10120 if (chr != str[i])
10121 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010122 /* This check keeps Python strings that end in '\0' from comparing equal
10123 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010125 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010126 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010127 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010128 return 0;
10129}
10130
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010131
Benjamin Peterson29060642009-01-31 22:14:21 +000010132#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010133 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010134
Alexander Belopolsky40018472011-02-26 01:02:56 +000010135PyObject *
10136PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010137{
10138 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010139
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010140 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10141 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (PyUnicode_READY(left) == -1 ||
10143 PyUnicode_READY(right) == -1)
10144 return NULL;
10145 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10146 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010147 if (op == Py_EQ) {
10148 Py_INCREF(Py_False);
10149 return Py_False;
10150 }
10151 if (op == Py_NE) {
10152 Py_INCREF(Py_True);
10153 return Py_True;
10154 }
10155 }
10156 if (left == right)
10157 result = 0;
10158 else
10159 result = unicode_compare((PyUnicodeObject *)left,
10160 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010161
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010162 /* Convert the return value to a Boolean */
10163 switch (op) {
10164 case Py_EQ:
10165 v = TEST_COND(result == 0);
10166 break;
10167 case Py_NE:
10168 v = TEST_COND(result != 0);
10169 break;
10170 case Py_LE:
10171 v = TEST_COND(result <= 0);
10172 break;
10173 case Py_GE:
10174 v = TEST_COND(result >= 0);
10175 break;
10176 case Py_LT:
10177 v = TEST_COND(result == -1);
10178 break;
10179 case Py_GT:
10180 v = TEST_COND(result == 1);
10181 break;
10182 default:
10183 PyErr_BadArgument();
10184 return NULL;
10185 }
10186 Py_INCREF(v);
10187 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010188 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010189
Brian Curtindfc80e32011-08-10 20:28:54 -050010190 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010191}
10192
Alexander Belopolsky40018472011-02-26 01:02:56 +000010193int
10194PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010195{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010196 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 int kind1, kind2, kind;
10198 void *buf1, *buf2;
10199 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010200 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010201
10202 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010203 sub = PyUnicode_FromObject(element);
10204 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010205 PyErr_Format(PyExc_TypeError,
10206 "'in <string>' requires string as left operand, not %s",
10207 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010209 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 if (PyUnicode_READY(sub) == -1)
10211 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010212
Thomas Wouters477c8d52006-05-27 19:21:47 +000010213 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010214 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010215 Py_DECREF(sub);
10216 return -1;
10217 }
10218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 kind1 = PyUnicode_KIND(str);
10220 kind2 = PyUnicode_KIND(sub);
10221 kind = kind1 > kind2 ? kind1 : kind2;
10222 buf1 = PyUnicode_DATA(str);
10223 buf2 = PyUnicode_DATA(sub);
10224 if (kind1 != kind)
10225 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10226 if (!buf1) {
10227 Py_DECREF(sub);
10228 return -1;
10229 }
10230 if (kind2 != kind)
10231 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10232 if (!buf2) {
10233 Py_DECREF(sub);
10234 if (kind1 != kind) PyMem_Free(buf1);
10235 return -1;
10236 }
10237 len1 = PyUnicode_GET_LENGTH(str);
10238 len2 = PyUnicode_GET_LENGTH(sub);
10239
10240 switch(kind) {
10241 case PyUnicode_1BYTE_KIND:
10242 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10243 break;
10244 case PyUnicode_2BYTE_KIND:
10245 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10246 break;
10247 case PyUnicode_4BYTE_KIND:
10248 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10249 break;
10250 default:
10251 result = -1;
10252 assert(0);
10253 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010254
10255 Py_DECREF(str);
10256 Py_DECREF(sub);
10257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 if (kind1 != kind)
10259 PyMem_Free(buf1);
10260 if (kind2 != kind)
10261 PyMem_Free(buf2);
10262
Guido van Rossum403d68b2000-03-13 15:55:09 +000010263 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010264}
10265
Guido van Rossumd57fd912000-03-10 22:53:23 +000010266/* Concat to string or Unicode object giving a new Unicode object. */
10267
Alexander Belopolsky40018472011-02-26 01:02:56 +000010268PyObject *
10269PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010270{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 PyObject *u = NULL, *v = NULL, *w;
10272 Py_UCS4 maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
10274 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010276 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010277 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010279 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010280 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281
10282 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010283 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010284 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010286 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010287 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010288 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290 }
10291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinnerff9e50f2011-09-28 22:17:19 +020010293 maxchar = Py_MAX(maxchar, PyUnicode_MAX_CHAR_VALUE(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 w = PyUnicode_New(
10297 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10298 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010300 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010301 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10302 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 Py_DECREF(u);
10304 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010305 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307
Benjamin Peterson29060642009-01-31 22:14:21 +000010308 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010309 Py_XDECREF(u);
10310 Py_XDECREF(v);
10311 return NULL;
10312}
10313
Victor Stinnerb0923652011-10-04 01:17:31 +020010314static void
10315unicode_append_inplace(PyObject **p_left, PyObject *right)
10316{
10317 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010318
10319 assert(PyUnicode_IS_READY(*p_left));
10320 assert(PyUnicode_IS_READY(right));
10321
10322 left_len = PyUnicode_GET_LENGTH(*p_left);
10323 right_len = PyUnicode_GET_LENGTH(right);
10324 if (left_len > PY_SSIZE_T_MAX - right_len) {
10325 PyErr_SetString(PyExc_OverflowError,
10326 "strings are too large to concat");
10327 goto error;
10328 }
10329 new_len = left_len + right_len;
10330
10331 /* Now we own the last reference to 'left', so we can resize it
10332 * in-place.
10333 */
10334 if (unicode_resize(p_left, new_len) != 0) {
10335 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10336 * deallocated so it cannot be put back into
10337 * 'variable'. The MemoryError is raised when there
10338 * is no value in 'variable', which might (very
10339 * remotely) be a cause of incompatibilities.
10340 */
10341 goto error;
10342 }
10343 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010344 copy_characters(*p_left, left_len, right, 0, right_len);
10345 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010346 return;
10347
10348error:
10349 Py_DECREF(*p_left);
10350 *p_left = NULL;
10351}
10352
Walter Dörwald1ab83302007-05-18 17:15:44 +000010353void
Victor Stinner23e56682011-10-03 03:54:37 +020010354PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010355{
Victor Stinner23e56682011-10-03 03:54:37 +020010356 PyObject *left, *res;
10357
10358 if (p_left == NULL) {
10359 if (!PyErr_Occurred())
10360 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010361 return;
10362 }
Victor Stinner23e56682011-10-03 03:54:37 +020010363 left = *p_left;
10364 if (right == NULL || !PyUnicode_Check(left)) {
10365 if (!PyErr_Occurred())
10366 PyErr_BadInternalCall();
10367 goto error;
10368 }
10369
Victor Stinnere1335c72011-10-04 20:53:03 +020010370 if (PyUnicode_READY(left))
10371 goto error;
10372 if (PyUnicode_READY(right))
10373 goto error;
10374
Victor Stinner23e56682011-10-03 03:54:37 +020010375 if (PyUnicode_CheckExact(left) && left != unicode_empty
10376 && PyUnicode_CheckExact(right) && right != unicode_empty
10377 && unicode_resizable(left)
10378 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10379 || _PyUnicode_WSTR(left) != NULL))
10380 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010381 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10382 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010383 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010384 not so different than duplicating the string. */
10385 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010386 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010387 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010388 if (p_left != NULL)
10389 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010390 return;
10391 }
10392 }
10393
10394 res = PyUnicode_Concat(left, right);
10395 if (res == NULL)
10396 goto error;
10397 Py_DECREF(left);
10398 *p_left = res;
10399 return;
10400
10401error:
10402 Py_DECREF(*p_left);
10403 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010404}
10405
10406void
10407PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10408{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010409 PyUnicode_Append(pleft, right);
10410 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010411}
10412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010413PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010414 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010417string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010418interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010419
10420static PyObject *
10421unicode_count(PyUnicodeObject *self, PyObject *args)
10422{
10423 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010424 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010425 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 int kind1, kind2, kind;
10428 void *buf1, *buf2;
10429 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430
Jesus Ceaac451502011-04-20 17:09:23 +020010431 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10432 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010433 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 kind1 = PyUnicode_KIND(self);
10436 kind2 = PyUnicode_KIND(substring);
10437 kind = kind1 > kind2 ? kind1 : kind2;
10438 buf1 = PyUnicode_DATA(self);
10439 buf2 = PyUnicode_DATA(substring);
10440 if (kind1 != kind)
10441 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10442 if (!buf1) {
10443 Py_DECREF(substring);
10444 return NULL;
10445 }
10446 if (kind2 != kind)
10447 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10448 if (!buf2) {
10449 Py_DECREF(substring);
10450 if (kind1 != kind) PyMem_Free(buf1);
10451 return NULL;
10452 }
10453 len1 = PyUnicode_GET_LENGTH(self);
10454 len2 = PyUnicode_GET_LENGTH(substring);
10455
10456 ADJUST_INDICES(start, end, len1);
10457 switch(kind) {
10458 case PyUnicode_1BYTE_KIND:
10459 iresult = ucs1lib_count(
10460 ((Py_UCS1*)buf1) + start, end - start,
10461 buf2, len2, PY_SSIZE_T_MAX
10462 );
10463 break;
10464 case PyUnicode_2BYTE_KIND:
10465 iresult = ucs2lib_count(
10466 ((Py_UCS2*)buf1) + start, end - start,
10467 buf2, len2, PY_SSIZE_T_MAX
10468 );
10469 break;
10470 case PyUnicode_4BYTE_KIND:
10471 iresult = ucs4lib_count(
10472 ((Py_UCS4*)buf1) + start, end - start,
10473 buf2, len2, PY_SSIZE_T_MAX
10474 );
10475 break;
10476 default:
10477 assert(0); iresult = 0;
10478 }
10479
10480 result = PyLong_FromSsize_t(iresult);
10481
10482 if (kind1 != kind)
10483 PyMem_Free(buf1);
10484 if (kind2 != kind)
10485 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486
10487 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010488
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489 return result;
10490}
10491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010492PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010493 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010495Encode S using the codec registered for encoding. Default encoding\n\
10496is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010497handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010498a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10499'xmlcharrefreplace' as well as any other name registered with\n\
10500codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501
10502static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010503unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010505 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506 char *encoding = NULL;
10507 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010508
Benjamin Peterson308d6372009-09-18 21:42:35 +000010509 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10510 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010512 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010513}
10514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010515PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010516 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010517\n\
10518Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010519If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520
10521static PyObject*
10522unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10523{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010524 Py_ssize_t i, j, line_pos, src_len, incr;
10525 Py_UCS4 ch;
10526 PyObject *u;
10527 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010529 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010530 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531
10532 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010533 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010534
Antoine Pitrou22425222011-10-04 19:10:51 +020010535 if (PyUnicode_READY(self) == -1)
10536 return NULL;
10537
Thomas Wouters7e474022000-07-16 12:04:32 +000010538 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010539 src_len = PyUnicode_GET_LENGTH(self);
10540 i = j = line_pos = 0;
10541 kind = PyUnicode_KIND(self);
10542 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010543 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010544 for (; i < src_len; i++) {
10545 ch = PyUnicode_READ(kind, src_data, i);
10546 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010547 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010548 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010549 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010550 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010551 goto overflow;
10552 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010553 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010554 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010555 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010557 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010558 goto overflow;
10559 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010561 if (ch == '\n' || ch == '\r')
10562 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010564 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010565 if (!found && PyUnicode_CheckExact(self)) {
10566 Py_INCREF((PyObject *) self);
10567 return (PyObject *) self;
10568 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010569
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010571 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572 if (!u)
10573 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010574 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010575
Antoine Pitroue71d5742011-10-04 15:55:09 +020010576 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010577
Antoine Pitroue71d5742011-10-04 15:55:09 +020010578 for (; i < src_len; i++) {
10579 ch = PyUnicode_READ(kind, src_data, i);
10580 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010581 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010582 incr = tabsize - (line_pos % tabsize);
10583 line_pos += incr;
10584 while (incr--) {
10585 PyUnicode_WRITE(kind, dest_data, j, ' ');
10586 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010587 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010589 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010590 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010591 line_pos++;
10592 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010593 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010594 if (ch == '\n' || ch == '\r')
10595 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010597 }
10598 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010599#ifndef DONT_MAKE_RESULT_READY
10600 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 Py_DECREF(u);
10602 return NULL;
10603 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010604#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010605 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010607
Antoine Pitroue71d5742011-10-04 15:55:09 +020010608 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010609 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10610 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611}
10612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010613PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010614 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615\n\
10616Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010617such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618arguments start and end are interpreted as in slice notation.\n\
10619\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010620Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621
10622static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010624{
Jesus Ceaac451502011-04-20 17:09:23 +020010625 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010626 Py_ssize_t start;
10627 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010628 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629
Jesus Ceaac451502011-04-20 17:09:23 +020010630 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10631 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 if (PyUnicode_READY(self) == -1)
10635 return NULL;
10636 if (PyUnicode_READY(substring) == -1)
10637 return NULL;
10638
Victor Stinner794d5672011-10-10 03:21:36 +020010639 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010641 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642
10643 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 if (result == -2)
10646 return NULL;
10647
Christian Heimes217cfd12007-12-02 14:31:20 +000010648 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010649}
10650
10651static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010652unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010654 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10655 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658}
10659
Guido van Rossumc2504932007-09-18 19:42:40 +000010660/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010010661 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000010662static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000010663unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664{
Guido van Rossumc2504932007-09-18 19:42:40 +000010665 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010010666 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 if (_PyUnicode_HASH(self) != -1)
10669 return _PyUnicode_HASH(self);
10670 if (PyUnicode_READY(self) == -1)
10671 return -1;
10672 len = PyUnicode_GET_LENGTH(self);
10673
10674 /* The hash function as a macro, gets expanded three times below. */
10675#define HASH(P) \
10676 x = (Py_uhash_t)*P << 7; \
10677 while (--len >= 0) \
10678 x = (1000003*x) ^ (Py_uhash_t)*P++;
10679
10680 switch (PyUnicode_KIND(self)) {
10681 case PyUnicode_1BYTE_KIND: {
10682 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
10683 HASH(c);
10684 break;
10685 }
10686 case PyUnicode_2BYTE_KIND: {
10687 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
10688 HASH(s);
10689 break;
10690 }
10691 default: {
10692 Py_UCS4 *l;
10693 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
10694 "Impossible switch case in unicode_hash");
10695 l = PyUnicode_4BYTE_DATA(self);
10696 HASH(l);
10697 break;
10698 }
10699 }
10700 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
10701
Guido van Rossumc2504932007-09-18 19:42:40 +000010702 if (x == -1)
10703 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010704 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000010705 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010709PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010710 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010711\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010712Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713
10714static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010717 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020010718 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010719 Py_ssize_t start;
10720 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721
Jesus Ceaac451502011-04-20 17:09:23 +020010722 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
10723 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726 if (PyUnicode_READY(self) == -1)
10727 return NULL;
10728 if (PyUnicode_READY(substring) == -1)
10729 return NULL;
10730
Victor Stinner794d5672011-10-10 03:21:36 +020010731 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000010733 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000010734
10735 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 if (result == -2)
10738 return NULL;
10739
Guido van Rossumd57fd912000-03-10 22:53:23 +000010740 if (result < 0) {
10741 PyErr_SetString(PyExc_ValueError, "substring not found");
10742 return NULL;
10743 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010744
Christian Heimes217cfd12007-12-02 14:31:20 +000010745 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010746}
10747
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010748PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010749 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010751Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010752at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010753
10754static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010755unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 Py_ssize_t i, length;
10758 int kind;
10759 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760 int cased;
10761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 if (PyUnicode_READY(self) == -1)
10763 return NULL;
10764 length = PyUnicode_GET_LENGTH(self);
10765 kind = PyUnicode_KIND(self);
10766 data = PyUnicode_DATA(self);
10767
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 if (length == 1)
10770 return PyBool_FromLong(
10771 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010772
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010773 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010775 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010776
Guido van Rossumd57fd912000-03-10 22:53:23 +000010777 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 for (i = 0; i < length; i++) {
10779 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010780
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
10782 return PyBool_FromLong(0);
10783 else if (!cased && Py_UNICODE_ISLOWER(ch))
10784 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010786 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010787}
10788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010789PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010790 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010791\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010792Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010793at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794
10795static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010796unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 Py_ssize_t i, length;
10799 int kind;
10800 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801 int cased;
10802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010803 if (PyUnicode_READY(self) == -1)
10804 return NULL;
10805 length = PyUnicode_GET_LENGTH(self);
10806 kind = PyUnicode_KIND(self);
10807 data = PyUnicode_DATA(self);
10808
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 if (length == 1)
10811 return PyBool_FromLong(
10812 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010814 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010816 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010817
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010819 for (i = 0; i < length; i++) {
10820 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010821
Benjamin Peterson29060642009-01-31 22:14:21 +000010822 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
10823 return PyBool_FromLong(0);
10824 else if (!cased && Py_UNICODE_ISUPPER(ch))
10825 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010827 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828}
10829
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010830PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010831 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010832\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010833Return True if S is a titlecased string and there is at least one\n\
10834character in S, i.e. upper- and titlecase characters may only\n\
10835follow uncased characters and lowercase characters only cased ones.\n\
10836Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010837
10838static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010839unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010841 Py_ssize_t i, length;
10842 int kind;
10843 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844 int cased, previous_is_cased;
10845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010846 if (PyUnicode_READY(self) == -1)
10847 return NULL;
10848 length = PyUnicode_GET_LENGTH(self);
10849 kind = PyUnicode_KIND(self);
10850 data = PyUnicode_DATA(self);
10851
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010853 if (length == 1) {
10854 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10855 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
10856 (Py_UNICODE_ISUPPER(ch) != 0));
10857 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010859 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010860 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010861 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010862
Guido van Rossumd57fd912000-03-10 22:53:23 +000010863 cased = 0;
10864 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010865 for (i = 0; i < length; i++) {
10866 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000010867
Benjamin Peterson29060642009-01-31 22:14:21 +000010868 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
10869 if (previous_is_cased)
10870 return PyBool_FromLong(0);
10871 previous_is_cased = 1;
10872 cased = 1;
10873 }
10874 else if (Py_UNICODE_ISLOWER(ch)) {
10875 if (!previous_is_cased)
10876 return PyBool_FromLong(0);
10877 previous_is_cased = 1;
10878 cased = 1;
10879 }
10880 else
10881 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010883 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884}
10885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010886PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010887 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010889Return True if all characters in S are whitespace\n\
10890and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010891
10892static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010893unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 Py_ssize_t i, length;
10896 int kind;
10897 void *data;
10898
10899 if (PyUnicode_READY(self) == -1)
10900 return NULL;
10901 length = PyUnicode_GET_LENGTH(self);
10902 kind = PyUnicode_KIND(self);
10903 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 if (length == 1)
10907 return PyBool_FromLong(
10908 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010910 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010911 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010912 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000010913
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010914 for (i = 0; i < length; i++) {
10915 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010916 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010917 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010919 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920}
10921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010922PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010923 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010924\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010925Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010926and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010927
10928static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010929unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 Py_ssize_t i, length;
10932 int kind;
10933 void *data;
10934
10935 if (PyUnicode_READY(self) == -1)
10936 return NULL;
10937 length = PyUnicode_GET_LENGTH(self);
10938 kind = PyUnicode_KIND(self);
10939 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010940
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010941 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 if (length == 1)
10943 return PyBool_FromLong(
10944 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010945
10946 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010948 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 for (i = 0; i < length; i++) {
10951 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000010952 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010953 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010954 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010955}
10956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010957PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010958 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010959\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000010960Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010961and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010962
10963static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010964unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010966 int kind;
10967 void *data;
10968 Py_ssize_t len, i;
10969
10970 if (PyUnicode_READY(self) == -1)
10971 return NULL;
10972
10973 kind = PyUnicode_KIND(self);
10974 data = PyUnicode_DATA(self);
10975 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010976
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010977 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 if (len == 1) {
10979 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
10980 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
10981 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010982
10983 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010986
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 for (i = 0; i < len; i++) {
10988 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030010989 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000010990 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010991 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000010992 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000010993}
10994
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010995PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000010998Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010999False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000
11001static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011002unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 Py_ssize_t i, length;
11005 int kind;
11006 void *data;
11007
11008 if (PyUnicode_READY(self) == -1)
11009 return NULL;
11010 length = PyUnicode_GET_LENGTH(self);
11011 kind = PyUnicode_KIND(self);
11012 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 if (length == 1)
11016 return PyBool_FromLong(
11017 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011019 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011020 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011021 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011023 for (i = 0; i < length; i++) {
11024 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011025 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011027 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028}
11029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011030PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011031 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011033Return True if all characters in S are digits\n\
11034and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035
11036static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011037unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011039 Py_ssize_t i, length;
11040 int kind;
11041 void *data;
11042
11043 if (PyUnicode_READY(self) == -1)
11044 return NULL;
11045 length = PyUnicode_GET_LENGTH(self);
11046 kind = PyUnicode_KIND(self);
11047 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011050 if (length == 1) {
11051 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11052 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11053 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011055 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011056 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011057 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 for (i = 0; i < length; i++) {
11060 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011061 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011062 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011063 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064}
11065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011066PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011067 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011069Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011070False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071
11072static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011073unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011075 Py_ssize_t i, length;
11076 int kind;
11077 void *data;
11078
11079 if (PyUnicode_READY(self) == -1)
11080 return NULL;
11081 length = PyUnicode_GET_LENGTH(self);
11082 kind = PyUnicode_KIND(self);
11083 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086 if (length == 1)
11087 return PyBool_FromLong(
11088 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011090 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011092 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 for (i = 0; i < length; i++) {
11095 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011096 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011098 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099}
11100
Martin v. Löwis47383402007-08-15 07:32:56 +000011101int
11102PyUnicode_IsIdentifier(PyObject *self)
11103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 int kind;
11105 void *data;
11106 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011107 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011109 if (PyUnicode_READY(self) == -1) {
11110 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011111 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112 }
11113
11114 /* Special case for empty strings */
11115 if (PyUnicode_GET_LENGTH(self) == 0)
11116 return 0;
11117 kind = PyUnicode_KIND(self);
11118 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011119
11120 /* PEP 3131 says that the first character must be in
11121 XID_Start and subsequent characters in XID_Continue,
11122 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011123 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011124 letters, digits, underscore). However, given the current
11125 definition of XID_Start and XID_Continue, it is sufficient
11126 to check just for these, except that _ must be allowed
11127 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011129 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011130 return 0;
11131
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011132 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011134 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011135 return 1;
11136}
11137
11138PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011139 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011140\n\
11141Return True if S is a valid identifier according\n\
11142to the language definition.");
11143
11144static PyObject*
11145unicode_isidentifier(PyObject *self)
11146{
11147 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11148}
11149
Georg Brandl559e5d72008-06-11 18:37:52 +000011150PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011151 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011152\n\
11153Return True if all characters in S are considered\n\
11154printable in repr() or S is empty, False otherwise.");
11155
11156static PyObject*
11157unicode_isprintable(PyObject *self)
11158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 Py_ssize_t i, length;
11160 int kind;
11161 void *data;
11162
11163 if (PyUnicode_READY(self) == -1)
11164 return NULL;
11165 length = PyUnicode_GET_LENGTH(self);
11166 kind = PyUnicode_KIND(self);
11167 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011168
11169 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (length == 1)
11171 return PyBool_FromLong(
11172 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 for (i = 0; i < length; i++) {
11175 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011176 Py_RETURN_FALSE;
11177 }
11178 }
11179 Py_RETURN_TRUE;
11180}
11181
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011182PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011183 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011184\n\
11185Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011186iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187
11188static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011189unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011191 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192}
11193
Martin v. Löwis18e16552006-02-15 17:27:45 +000011194static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195unicode_length(PyUnicodeObject *self)
11196{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (PyUnicode_READY(self) == -1)
11198 return -1;
11199 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200}
11201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011202PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011203 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011205Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011206done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011209unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011211 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011212 Py_UCS4 fillchar = ' ';
11213
11214 if (PyUnicode_READY(self) == -1)
11215 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011216
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011217 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218 return NULL;
11219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221 Py_INCREF(self);
11222 return (PyObject*) self;
11223 }
11224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226}
11227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011228PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011229 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011231Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232
11233static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011234unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 return fixup(self, fixlower);
11237}
11238
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011239#define LEFTSTRIP 0
11240#define RIGHTSTRIP 1
11241#define BOTHSTRIP 2
11242
11243/* Arrays indexed by above */
11244static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11245
11246#define STRIPNAME(i) (stripformat[i]+3)
11247
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011248/* externally visible for str.strip(unicode) */
11249PyObject *
11250_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11251{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011252 void *data;
11253 int kind;
11254 Py_ssize_t i, j, len;
11255 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011257 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11258 return NULL;
11259
11260 kind = PyUnicode_KIND(self);
11261 data = PyUnicode_DATA(self);
11262 len = PyUnicode_GET_LENGTH(self);
11263 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11264 PyUnicode_DATA(sepobj),
11265 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011266
Benjamin Peterson14339b62009-01-31 16:36:08 +000011267 i = 0;
11268 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 while (i < len &&
11270 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 i++;
11272 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011273 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011274
Benjamin Peterson14339b62009-01-31 16:36:08 +000011275 j = len;
11276 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 do {
11278 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 } while (j >= i &&
11280 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011281 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011282 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011283
Victor Stinner12bab6d2011-10-01 01:53:49 +020011284 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285}
11286
11287PyObject*
11288PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11289{
11290 unsigned char *data;
11291 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011292 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293
Victor Stinnerde636f32011-10-01 03:55:54 +020011294 if (PyUnicode_READY(self) == -1)
11295 return NULL;
11296
11297 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11298
Victor Stinner12bab6d2011-10-01 01:53:49 +020011299 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011301 if (PyUnicode_CheckExact(self)) {
11302 Py_INCREF(self);
11303 return self;
11304 }
11305 else
11306 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011307 }
11308
Victor Stinner12bab6d2011-10-01 01:53:49 +020011309 length = end - start;
11310 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011311 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312
Victor Stinnerde636f32011-10-01 03:55:54 +020011313 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011314 PyErr_SetString(PyExc_IndexError, "string index out of range");
11315 return NULL;
11316 }
11317
Victor Stinnerb9275c12011-10-05 14:01:42 +020011318 if (PyUnicode_IS_ASCII(self)) {
11319 kind = PyUnicode_KIND(self);
11320 data = PyUnicode_1BYTE_DATA(self);
11321 return unicode_fromascii(data + start, length);
11322 }
11323 else {
11324 kind = PyUnicode_KIND(self);
11325 data = PyUnicode_1BYTE_DATA(self);
11326 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011327 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011328 length);
11329 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331
11332static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011333do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 int kind;
11336 void *data;
11337 Py_ssize_t len, i, j;
11338
11339 if (PyUnicode_READY(self) == -1)
11340 return NULL;
11341
11342 kind = PyUnicode_KIND(self);
11343 data = PyUnicode_DATA(self);
11344 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011345
Benjamin Peterson14339b62009-01-31 16:36:08 +000011346 i = 0;
11347 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011349 i++;
11350 }
11351 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011352
Benjamin Peterson14339b62009-01-31 16:36:08 +000011353 j = len;
11354 if (striptype != LEFTSTRIP) {
11355 do {
11356 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011358 j++;
11359 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011360
Victor Stinner12bab6d2011-10-01 01:53:49 +020011361 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362}
11363
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011364
11365static PyObject *
11366do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11367{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011368 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011369
Benjamin Peterson14339b62009-01-31 16:36:08 +000011370 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11371 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011372
Benjamin Peterson14339b62009-01-31 16:36:08 +000011373 if (sep != NULL && sep != Py_None) {
11374 if (PyUnicode_Check(sep))
11375 return _PyUnicode_XStrip(self, striptype, sep);
11376 else {
11377 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 "%s arg must be None or str",
11379 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011380 return NULL;
11381 }
11382 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011383
Benjamin Peterson14339b62009-01-31 16:36:08 +000011384 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011385}
11386
11387
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011388PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011389 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011390\n\
11391Return a copy of the string S with leading and trailing\n\
11392whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011393If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011394
11395static PyObject *
11396unicode_strip(PyUnicodeObject *self, PyObject *args)
11397{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011398 if (PyTuple_GET_SIZE(args) == 0)
11399 return do_strip(self, BOTHSTRIP); /* Common case */
11400 else
11401 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011402}
11403
11404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011405PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011407\n\
11408Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011409If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011410
11411static PyObject *
11412unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11413{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011414 if (PyTuple_GET_SIZE(args) == 0)
11415 return do_strip(self, LEFTSTRIP); /* Common case */
11416 else
11417 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011418}
11419
11420
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011421PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011423\n\
11424Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011425If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011426
11427static PyObject *
11428unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11429{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011430 if (PyTuple_GET_SIZE(args) == 0)
11431 return do_strip(self, RIGHTSTRIP); /* Common case */
11432 else
11433 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011434}
11435
11436
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011438unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439{
11440 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Georg Brandl222de0f2009-04-12 12:01:50 +000011443 if (len < 1) {
11444 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011445 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011446 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447
Tim Peters7a29bd52001-09-12 03:03:31 +000011448 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 /* no repeat, return original string */
11450 Py_INCREF(str);
11451 return (PyObject*) str;
11452 }
Tim Peters8f422462000-09-09 06:13:41 +000011453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 if (PyUnicode_READY(str) == -1)
11455 return NULL;
11456
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011457 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011458 PyErr_SetString(PyExc_OverflowError,
11459 "repeated string is too long");
11460 return NULL;
11461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465 if (!u)
11466 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011467 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (PyUnicode_GET_LENGTH(str) == 1) {
11470 const int kind = PyUnicode_KIND(str);
11471 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11472 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011473 if (kind == PyUnicode_1BYTE_KIND)
11474 memset(to, (unsigned char)fill_char, len);
11475 else {
11476 for (n = 0; n < len; ++n)
11477 PyUnicode_WRITE(kind, to, n, fill_char);
11478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 }
11480 else {
11481 /* number of characters copied this far */
11482 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011483 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 char *to = (char *) PyUnicode_DATA(u);
11485 Py_MEMCPY(to, PyUnicode_DATA(str),
11486 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 n = (done <= nchars-done) ? done : nchars-done;
11489 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011490 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 }
11493
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011494 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495 return (PyObject*) u;
11496}
11497
Alexander Belopolsky40018472011-02-26 01:02:56 +000011498PyObject *
11499PyUnicode_Replace(PyObject *obj,
11500 PyObject *subobj,
11501 PyObject *replobj,
11502 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503{
11504 PyObject *self;
11505 PyObject *str1;
11506 PyObject *str2;
11507 PyObject *result;
11508
11509 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011510 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011513 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 Py_DECREF(self);
11515 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 }
11517 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011518 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 Py_DECREF(self);
11520 Py_DECREF(str1);
11521 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 Py_DECREF(self);
11525 Py_DECREF(str1);
11526 Py_DECREF(str2);
11527 return result;
11528}
11529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011531 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532\n\
11533Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011534old replaced by new. If the optional argument count is\n\
11535given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536
11537static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540 PyObject *str1;
11541 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011542 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543 PyObject *result;
11544
Martin v. Löwis18e16552006-02-15 17:27:45 +000011545 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 str1 = PyUnicode_FromObject(str1);
11550 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11551 return NULL;
11552 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011553 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 Py_DECREF(str1);
11555 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011556 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557
11558 result = replace(self, str1, str2, maxcount);
11559
11560 Py_DECREF(str1);
11561 Py_DECREF(str2);
11562 return result;
11563}
11564
Alexander Belopolsky40018472011-02-26 01:02:56 +000011565static PyObject *
11566unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011568 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011569 Py_ssize_t isize;
11570 Py_ssize_t osize, squote, dquote, i, o;
11571 Py_UCS4 max, quote;
11572 int ikind, okind;
11573 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011574
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011576 return NULL;
11577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 isize = PyUnicode_GET_LENGTH(unicode);
11579 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 /* Compute length of output, quote characters, and
11582 maximum character */
11583 osize = 2; /* quotes */
11584 max = 127;
11585 squote = dquote = 0;
11586 ikind = PyUnicode_KIND(unicode);
11587 for (i = 0; i < isize; i++) {
11588 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11589 switch (ch) {
11590 case '\'': squote++; osize++; break;
11591 case '"': dquote++; osize++; break;
11592 case '\\': case '\t': case '\r': case '\n':
11593 osize += 2; break;
11594 default:
11595 /* Fast-path ASCII */
11596 if (ch < ' ' || ch == 0x7f)
11597 osize += 4; /* \xHH */
11598 else if (ch < 0x7f)
11599 osize++;
11600 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11601 osize++;
11602 max = ch > max ? ch : max;
11603 }
11604 else if (ch < 0x100)
11605 osize += 4; /* \xHH */
11606 else if (ch < 0x10000)
11607 osize += 6; /* \uHHHH */
11608 else
11609 osize += 10; /* \uHHHHHHHH */
11610 }
11611 }
11612
11613 quote = '\'';
11614 if (squote) {
11615 if (dquote)
11616 /* Both squote and dquote present. Use squote,
11617 and escape them */
11618 osize += squote;
11619 else
11620 quote = '"';
11621 }
11622
11623 repr = PyUnicode_New(osize, max);
11624 if (repr == NULL)
11625 return NULL;
11626 okind = PyUnicode_KIND(repr);
11627 odata = PyUnicode_DATA(repr);
11628
11629 PyUnicode_WRITE(okind, odata, 0, quote);
11630 PyUnicode_WRITE(okind, odata, osize-1, quote);
11631
11632 for (i = 0, o = 1; i < isize; i++) {
11633 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011634
11635 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if ((ch == quote) || (ch == '\\')) {
11637 PyUnicode_WRITE(okind, odata, o++, '\\');
11638 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011639 continue;
11640 }
11641
Benjamin Peterson29060642009-01-31 22:14:21 +000011642 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011643 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 PyUnicode_WRITE(okind, odata, o++, '\\');
11645 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011646 }
11647 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 PyUnicode_WRITE(okind, odata, o++, '\\');
11649 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011650 }
11651 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 PyUnicode_WRITE(okind, odata, o++, '\\');
11653 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011654 }
11655
11656 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011657 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011658 PyUnicode_WRITE(okind, odata, o++, '\\');
11659 PyUnicode_WRITE(okind, odata, o++, 'x');
11660 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11661 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011662 }
11663
Georg Brandl559e5d72008-06-11 18:37:52 +000011664 /* Copy ASCII characters as-is */
11665 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011667 }
11668
Benjamin Peterson29060642009-01-31 22:14:21 +000011669 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000011670 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011671 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000011672 (categories Z* and C* except ASCII space)
11673 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011675 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 if (ch <= 0xff) {
11677 PyUnicode_WRITE(okind, odata, o++, '\\');
11678 PyUnicode_WRITE(okind, odata, o++, 'x');
11679 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0x000F]);
11680 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011681 }
11682 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 else if (ch >= 0x10000) {
11684 PyUnicode_WRITE(okind, odata, o++, '\\');
11685 PyUnicode_WRITE(okind, odata, o++, 'U');
11686 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 28) & 0xF]);
11687 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 24) & 0xF]);
11688 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 20) & 0xF]);
11689 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 16) & 0xF]);
11690 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11691 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11692 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11693 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011694 }
11695 /* Map 16-bit characters to '\uxxxx' */
11696 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 PyUnicode_WRITE(okind, odata, o++, '\\');
11698 PyUnicode_WRITE(okind, odata, o++, 'u');
11699 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 12) & 0xF]);
11700 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 8) & 0xF]);
11701 PyUnicode_WRITE(okind, odata, o++, hexdigits[(ch >> 4) & 0xF]);
11702 PyUnicode_WRITE(okind, odata, o++, hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000011703 }
11704 }
11705 /* Copy characters as-is */
11706 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000011708 }
11709 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000011710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020011712 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000011713 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714}
11715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011716PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011717 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718\n\
11719Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011720such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721arguments start and end are interpreted as in slice notation.\n\
11722\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011723Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724
11725static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727{
Jesus Ceaac451502011-04-20 17:09:23 +020011728 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011729 Py_ssize_t start;
11730 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011731 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
Jesus Ceaac451502011-04-20 17:09:23 +020011733 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
11734 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011735 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 if (PyUnicode_READY(self) == -1)
11738 return NULL;
11739 if (PyUnicode_READY(substring) == -1)
11740 return NULL;
11741
Victor Stinner794d5672011-10-10 03:21:36 +020011742 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011744 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745
11746 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 if (result == -2)
11749 return NULL;
11750
Christian Heimes217cfd12007-12-02 14:31:20 +000011751 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752}
11753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011754PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011755 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011757Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758
11759static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761{
Jesus Ceaac451502011-04-20 17:09:23 +020011762 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011763 Py_ssize_t start;
11764 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011765 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766
Jesus Ceaac451502011-04-20 17:09:23 +020011767 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
11768 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000011769 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 if (PyUnicode_READY(self) == -1)
11772 return NULL;
11773 if (PyUnicode_READY(substring) == -1)
11774 return NULL;
11775
Victor Stinner794d5672011-10-10 03:21:36 +020011776 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011778 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
11780 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 if (result == -2)
11783 return NULL;
11784
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 if (result < 0) {
11786 PyErr_SetString(PyExc_ValueError, "substring not found");
11787 return NULL;
11788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789
Christian Heimes217cfd12007-12-02 14:31:20 +000011790 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791}
11792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011793PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011794 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011796Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011797done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
11799static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011800unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011802 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 Py_UCS4 fillchar = ' ';
11804
Victor Stinnere9a29352011-10-01 02:14:59 +020011805 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011807
Victor Stinnere9a29352011-10-01 02:14:59 +020011808 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809 return NULL;
11810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812 Py_INCREF(self);
11813 return (PyObject*) self;
11814 }
11815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817}
11818
Alexander Belopolsky40018472011-02-26 01:02:56 +000011819PyObject *
11820PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821{
11822 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000011823
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824 s = PyUnicode_FromObject(s);
11825 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000011826 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 if (sep != NULL) {
11828 sep = PyUnicode_FromObject(sep);
11829 if (sep == NULL) {
11830 Py_DECREF(s);
11831 return NULL;
11832 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 }
11834
Victor Stinner9310abb2011-10-05 00:59:23 +020011835 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836
11837 Py_DECREF(s);
11838 Py_XDECREF(sep);
11839 return result;
11840}
11841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011842PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011843 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844\n\
11845Return a list of the words in S, using sep as the\n\
11846delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000011847splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000011848whitespace string is a separator and empty strings are\n\
11849removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850
11851static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011852unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853{
11854 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011855 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856
Martin v. Löwis18e16552006-02-15 17:27:45 +000011857 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858 return NULL;
11859
11860 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000011861 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020011863 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864 else
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866}
11867
Thomas Wouters477c8d52006-05-27 19:21:47 +000011868PyObject *
11869PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
11870{
11871 PyObject* str_obj;
11872 PyObject* sep_obj;
11873 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 int kind1, kind2, kind;
11875 void *buf1 = NULL, *buf2 = NULL;
11876 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011877
11878 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020011879 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011881 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011883 Py_DECREF(str_obj);
11884 return NULL;
11885 }
11886
Victor Stinner14f8f022011-10-05 20:58:25 +020011887 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020011889 kind = Py_MAX(kind1, kind2);
11890 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020011892 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 if (!buf1)
11894 goto onError;
11895 buf2 = PyUnicode_DATA(sep_obj);
11896 if (kind2 != kind)
11897 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11898 if (!buf2)
11899 goto onError;
11900 len1 = PyUnicode_GET_LENGTH(str_obj);
11901 len2 = PyUnicode_GET_LENGTH(sep_obj);
11902
Victor Stinner14f8f022011-10-05 20:58:25 +020011903 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011904 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011905 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11906 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11907 else
11908 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 break;
11910 case PyUnicode_2BYTE_KIND:
11911 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11912 break;
11913 case PyUnicode_4BYTE_KIND:
11914 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
11915 break;
11916 default:
11917 assert(0);
11918 out = 0;
11919 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011920
11921 Py_DECREF(sep_obj);
11922 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011923 if (kind1 != kind)
11924 PyMem_Free(buf1);
11925 if (kind2 != kind)
11926 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011927
11928 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 onError:
11930 Py_DECREF(sep_obj);
11931 Py_DECREF(str_obj);
11932 if (kind1 != kind && buf1)
11933 PyMem_Free(buf1);
11934 if (kind2 != kind && buf2)
11935 PyMem_Free(buf2);
11936 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011937}
11938
11939
11940PyObject *
11941PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
11942{
11943 PyObject* str_obj;
11944 PyObject* sep_obj;
11945 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 int kind1, kind2, kind;
11947 void *buf1 = NULL, *buf2 = NULL;
11948 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011949
11950 str_obj = PyUnicode_FromObject(str_in);
11951 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000011952 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011953 sep_obj = PyUnicode_FromObject(sep_in);
11954 if (!sep_obj) {
11955 Py_DECREF(str_obj);
11956 return NULL;
11957 }
11958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 kind1 = PyUnicode_KIND(str_in);
11960 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020011961 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 buf1 = PyUnicode_DATA(str_in);
11963 if (kind1 != kind)
11964 buf1 = _PyUnicode_AsKind(str_in, kind);
11965 if (!buf1)
11966 goto onError;
11967 buf2 = PyUnicode_DATA(sep_obj);
11968 if (kind2 != kind)
11969 buf2 = _PyUnicode_AsKind(sep_obj, kind);
11970 if (!buf2)
11971 goto onError;
11972 len1 = PyUnicode_GET_LENGTH(str_obj);
11973 len2 = PyUnicode_GET_LENGTH(sep_obj);
11974
11975 switch(PyUnicode_KIND(str_in)) {
11976 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020011977 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
11978 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11979 else
11980 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 break;
11982 case PyUnicode_2BYTE_KIND:
11983 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11984 break;
11985 case PyUnicode_4BYTE_KIND:
11986 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
11987 break;
11988 default:
11989 assert(0);
11990 out = 0;
11991 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011992
11993 Py_DECREF(sep_obj);
11994 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 if (kind1 != kind)
11996 PyMem_Free(buf1);
11997 if (kind2 != kind)
11998 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011999
12000 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 onError:
12002 Py_DECREF(sep_obj);
12003 Py_DECREF(str_obj);
12004 if (kind1 != kind && buf1)
12005 PyMem_Free(buf1);
12006 if (kind2 != kind && buf2)
12007 PyMem_Free(buf2);
12008 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012009}
12010
12011PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012012 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012013\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012014Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012015the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012016found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012017
12018static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012019unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012020{
Victor Stinner9310abb2011-10-05 00:59:23 +020012021 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012022}
12023
12024PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012025 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012026\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012027Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012028the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012029separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012030
12031static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012032unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012033{
Victor Stinner9310abb2011-10-05 00:59:23 +020012034 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012035}
12036
Alexander Belopolsky40018472011-02-26 01:02:56 +000012037PyObject *
12038PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012039{
12040 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012041
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012042 s = PyUnicode_FromObject(s);
12043 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012044 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012045 if (sep != NULL) {
12046 sep = PyUnicode_FromObject(sep);
12047 if (sep == NULL) {
12048 Py_DECREF(s);
12049 return NULL;
12050 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012051 }
12052
Victor Stinner9310abb2011-10-05 00:59:23 +020012053 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012054
12055 Py_DECREF(s);
12056 Py_XDECREF(sep);
12057 return result;
12058}
12059
12060PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012061 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012062\n\
12063Return a list of the words in S, using sep as the\n\
12064delimiter string, starting at the end of the string and\n\
12065working to the front. If maxsplit is given, at most maxsplit\n\
12066splits are done. If sep is not specified, any whitespace string\n\
12067is a separator.");
12068
12069static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012070unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012071{
12072 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012073 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012074
Martin v. Löwis18e16552006-02-15 17:27:45 +000012075 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012076 return NULL;
12077
12078 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012079 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012080 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012081 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012082 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012083 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012084}
12085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012086PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012087 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012088\n\
12089Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012090Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012091is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012094unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012096 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012097 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012099 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12100 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101 return NULL;
12102
Guido van Rossum86662912000-04-11 15:38:46 +000012103 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104}
12105
12106static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012107PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108{
Walter Dörwald346737f2007-05-31 10:44:43 +000012109 if (PyUnicode_CheckExact(self)) {
12110 Py_INCREF(self);
12111 return self;
12112 } else
12113 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012114 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115}
12116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012117PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012118 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119\n\
12120Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012121and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122
12123static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012124unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126 return fixup(self, fixswapcase);
12127}
12128
Georg Brandlceee0772007-11-27 23:48:05 +000012129PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012130 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012131\n\
12132Return a translation table usable for str.translate().\n\
12133If there is only one argument, it must be a dictionary mapping Unicode\n\
12134ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012135Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012136If there are two arguments, they must be strings of equal length, and\n\
12137in the resulting dictionary, each character in x will be mapped to the\n\
12138character at the same position in y. If there is a third argument, it\n\
12139must be a string, whose characters will be mapped to None in the result.");
12140
12141static PyObject*
12142unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12143{
12144 PyObject *x, *y = NULL, *z = NULL;
12145 PyObject *new = NULL, *key, *value;
12146 Py_ssize_t i = 0;
12147 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012148
Georg Brandlceee0772007-11-27 23:48:05 +000012149 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12150 return NULL;
12151 new = PyDict_New();
12152 if (!new)
12153 return NULL;
12154 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 int x_kind, y_kind, z_kind;
12156 void *x_data, *y_data, *z_data;
12157
Georg Brandlceee0772007-11-27 23:48:05 +000012158 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012159 if (!PyUnicode_Check(x)) {
12160 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12161 "be a string if there is a second argument");
12162 goto err;
12163 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012165 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12166 "arguments must have equal length");
12167 goto err;
12168 }
12169 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 x_kind = PyUnicode_KIND(x);
12171 y_kind = PyUnicode_KIND(y);
12172 x_data = PyUnicode_DATA(x);
12173 y_data = PyUnicode_DATA(y);
12174 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12175 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12176 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012177 if (!key || !value)
12178 goto err;
12179 res = PyDict_SetItem(new, key, value);
12180 Py_DECREF(key);
12181 Py_DECREF(value);
12182 if (res < 0)
12183 goto err;
12184 }
12185 /* create entries for deleting chars in z */
12186 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012187 z_kind = PyUnicode_KIND(z);
12188 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012189 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012191 if (!key)
12192 goto err;
12193 res = PyDict_SetItem(new, key, Py_None);
12194 Py_DECREF(key);
12195 if (res < 0)
12196 goto err;
12197 }
12198 }
12199 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 int kind;
12201 void *data;
12202
Georg Brandlceee0772007-11-27 23:48:05 +000012203 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012204 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012205 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12206 "to maketrans it must be a dict");
12207 goto err;
12208 }
12209 /* copy entries into the new dict, converting string keys to int keys */
12210 while (PyDict_Next(x, &i, &key, &value)) {
12211 if (PyUnicode_Check(key)) {
12212 /* convert string keys to integer keys */
12213 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012214 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012215 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12216 "table must be of length 1");
12217 goto err;
12218 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 kind = PyUnicode_KIND(key);
12220 data = PyUnicode_DATA(key);
12221 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012222 if (!newkey)
12223 goto err;
12224 res = PyDict_SetItem(new, newkey, value);
12225 Py_DECREF(newkey);
12226 if (res < 0)
12227 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012228 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012229 /* just keep integer keys */
12230 if (PyDict_SetItem(new, key, value) < 0)
12231 goto err;
12232 } else {
12233 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12234 "be strings or integers");
12235 goto err;
12236 }
12237 }
12238 }
12239 return new;
12240 err:
12241 Py_DECREF(new);
12242 return NULL;
12243}
12244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012245PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247\n\
12248Return a copy of the string S, where all characters have been mapped\n\
12249through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012250Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012251Unmapped characters are left untouched. Characters mapped to None\n\
12252are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
12254static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258}
12259
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012260PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012261 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012263Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
12265static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012266unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268 return fixup(self, fixupper);
12269}
12270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012271PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012272 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012274Pad a numeric string S with zeros on the left, to fill a field\n\
12275of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276
12277static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012278unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012280 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012281 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012282 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 int kind;
12284 void *data;
12285 Py_UCS4 chr;
12286
12287 if (PyUnicode_READY(self) == -1)
12288 return NULL;
12289
Martin v. Löwis18e16552006-02-15 17:27:45 +000012290 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291 return NULL;
12292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012294 if (PyUnicode_CheckExact(self)) {
12295 Py_INCREF(self);
12296 return (PyObject*) self;
12297 }
12298 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012299 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300 }
12301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303
12304 u = pad(self, fill, 0, '0');
12305
Walter Dörwald068325e2002-04-15 13:36:47 +000012306 if (u == NULL)
12307 return NULL;
12308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 kind = PyUnicode_KIND(u);
12310 data = PyUnicode_DATA(u);
12311 chr = PyUnicode_READ(kind, data, fill);
12312
12313 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 PyUnicode_WRITE(kind, data, 0, chr);
12316 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317 }
12318
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012319 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320 return (PyObject*) u;
12321}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322
12323#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012324static PyObject *
12325unicode__decimal2ascii(PyObject *self)
12326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012328}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012329#endif
12330
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012331PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012332 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012333\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012334Return True if S starts with the specified prefix, False otherwise.\n\
12335With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012336With optional end, stop comparing S at that position.\n\
12337prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338
12339static PyObject *
12340unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012341 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012342{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012343 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012345 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012346 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012347 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348
Jesus Ceaac451502011-04-20 17:09:23 +020012349 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012350 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012351 if (PyTuple_Check(subobj)) {
12352 Py_ssize_t i;
12353 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12354 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012355 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012356 if (substring == NULL)
12357 return NULL;
12358 result = tailmatch(self, substring, start, end, -1);
12359 Py_DECREF(substring);
12360 if (result) {
12361 Py_RETURN_TRUE;
12362 }
12363 }
12364 /* nothing matched */
12365 Py_RETURN_FALSE;
12366 }
12367 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012368 if (substring == NULL) {
12369 if (PyErr_ExceptionMatches(PyExc_TypeError))
12370 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12371 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012372 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012373 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012374 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012376 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377}
12378
12379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012380PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012382\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012383Return True if S ends with the specified suffix, False otherwise.\n\
12384With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012385With optional end, stop comparing S at that position.\n\
12386suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387
12388static PyObject *
12389unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012392 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012394 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012395 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012396 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
Jesus Ceaac451502011-04-20 17:09:23 +020012398 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012399 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012400 if (PyTuple_Check(subobj)) {
12401 Py_ssize_t i;
12402 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12403 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012405 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012406 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012407 result = tailmatch(self, substring, start, end, +1);
12408 Py_DECREF(substring);
12409 if (result) {
12410 Py_RETURN_TRUE;
12411 }
12412 }
12413 Py_RETURN_FALSE;
12414 }
12415 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012416 if (substring == NULL) {
12417 if (PyErr_ExceptionMatches(PyExc_TypeError))
12418 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12419 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012421 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012422 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012424 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012425}
12426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012428
12429PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012430 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012431\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012432Return a formatted version of S, using substitutions from args and kwargs.\n\
12433The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012434
Eric Smith27bbca62010-11-04 17:06:58 +000012435PyDoc_STRVAR(format_map__doc__,
12436 "S.format_map(mapping) -> str\n\
12437\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012438Return a formatted version of S, using substitutions from mapping.\n\
12439The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012440
Eric Smith4a7d76d2008-05-30 18:10:19 +000012441static PyObject *
12442unicode__format__(PyObject* self, PyObject* args)
12443{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012444 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012445
12446 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12447 return NULL;
12448
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012449 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012451 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012452}
12453
Eric Smith8c663262007-08-25 02:26:07 +000012454PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012455 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012456\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012457Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012458
12459static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012460unicode__sizeof__(PyUnicodeObject *v)
12461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 Py_ssize_t size;
12463
12464 /* If it's a compact object, account for base structure +
12465 character data. */
12466 if (PyUnicode_IS_COMPACT_ASCII(v))
12467 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12468 else if (PyUnicode_IS_COMPACT(v))
12469 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012470 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 else {
12472 /* If it is a two-block object, account for base object, and
12473 for character block if present. */
12474 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012475 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012477 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 }
12479 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012480 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012481 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012483 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012484 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485
12486 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012487}
12488
12489PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012490 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012491
12492static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012493unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012494{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012495 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012496 if (!copy)
12497 return NULL;
12498 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012499}
12500
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501static PyMethodDef unicode_methods[] = {
12502
12503 /* Order is according to common usage: often used methods should
12504 appear first, since lookup is done sequentially. */
12505
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012506 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012507 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12508 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012509 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012510 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12511 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12512 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12513 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12514 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12515 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12516 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012517 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012518 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12519 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12520 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012521 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012522 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12523 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12524 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012525 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012527 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012528 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012529 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12530 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12531 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12532 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12533 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12534 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12535 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12536 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12537 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12538 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12539 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12540 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12541 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12542 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012543 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012544 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012545 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012546 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012547 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012548 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012549 {"maketrans", (PyCFunction) unicode_maketrans,
12550 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012551 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012552#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012553 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554#endif
12555
12556#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012557 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012558 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559#endif
12560
Benjamin Peterson14339b62009-01-31 16:36:08 +000012561 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562 {NULL, NULL}
12563};
12564
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012565static PyObject *
12566unicode_mod(PyObject *v, PyObject *w)
12567{
Brian Curtindfc80e32011-08-10 20:28:54 -050012568 if (!PyUnicode_Check(v))
12569 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012570 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012571}
12572
12573static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012574 0, /*nb_add*/
12575 0, /*nb_subtract*/
12576 0, /*nb_multiply*/
12577 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012578};
12579
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012581 (lenfunc) unicode_length, /* sq_length */
12582 PyUnicode_Concat, /* sq_concat */
12583 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12584 (ssizeargfunc) unicode_getitem, /* sq_item */
12585 0, /* sq_slice */
12586 0, /* sq_ass_item */
12587 0, /* sq_ass_slice */
12588 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589};
12590
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012591static PyObject*
12592unicode_subscript(PyUnicodeObject* self, PyObject* item)
12593{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 if (PyUnicode_READY(self) == -1)
12595 return NULL;
12596
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012597 if (PyIndex_Check(item)) {
12598 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012599 if (i == -1 && PyErr_Occurred())
12600 return NULL;
12601 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020012603 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012604 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012605 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012606 PyObject *result;
12607 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012608 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012609 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012610
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012612 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012613 return NULL;
12614 }
12615
12616 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012617 return PyUnicode_New(0, 0);
12618 } else if (start == 0 && step == 1 &&
12619 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012620 PyUnicode_CheckExact(self)) {
12621 Py_INCREF(self);
12622 return (PyObject *)self;
12623 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012624 return PyUnicode_Substring((PyObject*)self,
12625 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012626 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012627 /* General case */
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012628 max_char = 0;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012629 src_kind = PyUnicode_KIND(self);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012630 kind_limit = kind_maxchar_limit(src_kind);
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012631 src_data = PyUnicode_DATA(self);
12632 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12633 ch = PyUnicode_READ(src_kind, src_data, cur);
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012634 if (ch > max_char) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012635 max_char = ch;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012636 if (max_char >= kind_limit)
12637 break;
12638 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012639 }
12640 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012641 if (result == NULL)
12642 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012643 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012644 dest_data = PyUnicode_DATA(result);
12645
12646 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012647 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12648 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012649 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012650 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012651 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012652 } else {
12653 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12654 return NULL;
12655 }
12656}
12657
12658static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012659 (lenfunc)unicode_length, /* mp_length */
12660 (binaryfunc)unicode_subscript, /* mp_subscript */
12661 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012662};
12663
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665/* Helpers for PyUnicode_Format() */
12666
12667static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000012668getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012670 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012672 (*p_argidx)++;
12673 if (arglen < 0)
12674 return args;
12675 else
12676 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677 }
12678 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012679 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680 return NULL;
12681}
12682
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012683/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012685static PyObject *
12686formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012688 char *p;
12689 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690 double x;
Tim Petersced69f82003-09-16 20:30:58 +000012691
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692 x = PyFloat_AsDouble(v);
12693 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012694 return NULL;
12695
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012697 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000012698
Eric Smith0923d1d2009-04-16 20:16:10 +000012699 p = PyOS_double_to_string(x, type, prec,
12700 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000012701 if (p == NULL)
12702 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000012704 PyMem_Free(p);
12705 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706}
12707
Tim Peters38fd5b62000-09-21 05:43:11 +000012708static PyObject*
12709formatlong(PyObject *val, int flags, int prec, int type)
12710{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012711 char *buf;
12712 int len;
12713 PyObject *str; /* temporary string object. */
12714 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012715
Benjamin Peterson14339b62009-01-31 16:36:08 +000012716 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
12717 if (!str)
12718 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000012720 Py_DECREF(str);
12721 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000012722}
12723
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012724static Py_UCS4
12725formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012727 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012728 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012730 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000012731 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 goto onError;
12733 }
12734 else {
12735 /* Integer input truncated to a character */
12736 long x;
12737 x = PyLong_AsLong(v);
12738 if (x == -1 && PyErr_Occurred())
12739 goto onError;
12740
12741 if (x < 0 || x > 0x10ffff) {
12742 PyErr_SetString(PyExc_OverflowError,
12743 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012744 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012745 }
12746
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012747 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012748 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000012749
Benjamin Peterson29060642009-01-31 22:14:21 +000012750 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000012751 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012753 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754}
12755
Antoine Pitrou978b9d22011-10-07 12:35:48 +020012756static int
12757repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
12758{
12759 int r;
12760 assert(count > 0);
12761 assert(PyUnicode_Check(obj));
12762 if (count > 5) {
12763 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
12764 if (repeated == NULL)
12765 return -1;
12766 r = _PyAccu_Accumulate(acc, repeated);
12767 Py_DECREF(repeated);
12768 return r;
12769 }
12770 else {
12771 do {
12772 if (_PyAccu_Accumulate(acc, obj))
12773 return -1;
12774 } while (--count);
12775 return 0;
12776 }
12777}
12778
Alexander Belopolsky40018472011-02-26 01:02:56 +000012779PyObject *
12780PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782 void *fmt;
12783 int fmtkind;
12784 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012785 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012786 int r;
12787 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012788 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012790 PyObject *temp = NULL;
12791 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012792 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012793 _PyAccu acc;
12794 static PyObject *plus, *minus, *blank, *zero, *percent;
12795
12796 if (!plus && !(plus = get_latin1_char('+')))
12797 return NULL;
12798 if (!minus && !(minus = get_latin1_char('-')))
12799 return NULL;
12800 if (!blank && !(blank = get_latin1_char(' ')))
12801 return NULL;
12802 if (!zero && !(zero = get_latin1_char('0')))
12803 return NULL;
12804 if (!percent && !(percent = get_latin1_char('%')))
12805 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000012806
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012808 PyErr_BadInternalCall();
12809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012811 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
12812 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012814 if (_PyAccu_Init(&acc))
12815 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012816 fmt = PyUnicode_DATA(uformat);
12817 fmtkind = PyUnicode_KIND(uformat);
12818 fmtcnt = PyUnicode_GET_LENGTH(uformat);
12819 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820
Guido van Rossumd57fd912000-03-10 22:53:23 +000012821 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 arglen = PyTuple_Size(args);
12823 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824 }
12825 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 arglen = -1;
12827 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828 }
Christian Heimes90aa7642007-12-19 02:45:37 +000012829 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000012830 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000012831 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832
12833 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012835 PyObject *nonfmt;
12836 Py_ssize_t nonfmtpos;
12837 nonfmtpos = fmtpos++;
12838 while (fmtcnt >= 0 &&
12839 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
12840 fmtpos++;
12841 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012842 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012843 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
12844 if (nonfmt == NULL)
12845 goto onError;
12846 r = _PyAccu_Accumulate(&acc, nonfmt);
12847 Py_DECREF(nonfmt);
12848 if (r)
12849 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012850 }
12851 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 /* Got a format specifier */
12853 int flags = 0;
12854 Py_ssize_t width = -1;
12855 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012857 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000012858 int isnumok;
12859 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020012860 void *pbuf = NULL;
12861 Py_ssize_t pindex, len;
12862 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864 fmtpos++;
12865 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
12866 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000012867 Py_ssize_t keylen;
12868 PyObject *key;
12869 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000012870
Benjamin Peterson29060642009-01-31 22:14:21 +000012871 if (dict == NULL) {
12872 PyErr_SetString(PyExc_TypeError,
12873 "format requires a mapping");
12874 goto onError;
12875 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000012879 /* Skip over balanced parentheses */
12880 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012881 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000012882 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012887 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000012888 if (fmtcnt < 0 || pcount > 0) {
12889 PyErr_SetString(PyExc_ValueError,
12890 "incomplete format key");
12891 goto onError;
12892 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020012893 key = PyUnicode_Substring((PyObject*)uformat,
12894 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 if (key == NULL)
12896 goto onError;
12897 if (args_owned) {
12898 Py_DECREF(args);
12899 args_owned = 0;
12900 }
12901 args = PyObject_GetItem(dict, key);
12902 Py_DECREF(key);
12903 if (args == NULL) {
12904 goto onError;
12905 }
12906 args_owned = 1;
12907 arglen = -1;
12908 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012909 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012911 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012912 case '-': flags |= F_LJUST; continue;
12913 case '+': flags |= F_SIGN; continue;
12914 case ' ': flags |= F_BLANK; continue;
12915 case '#': flags |= F_ALT; continue;
12916 case '0': flags |= F_ZERO; continue;
12917 }
12918 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012919 }
Benjamin Peterson29060642009-01-31 22:14:21 +000012920 if (c == '*') {
12921 v = getnextarg(args, arglen, &argidx);
12922 if (v == NULL)
12923 goto onError;
12924 if (!PyLong_Check(v)) {
12925 PyErr_SetString(PyExc_TypeError,
12926 "* wants int");
12927 goto onError;
12928 }
12929 width = PyLong_AsLong(v);
12930 if (width == -1 && PyErr_Occurred())
12931 goto onError;
12932 if (width < 0) {
12933 flags |= F_LJUST;
12934 width = -width;
12935 }
12936 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012938 }
12939 else if (c >= '0' && c <= '9') {
12940 width = c - '0';
12941 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 if (c < '0' || c > '9')
12944 break;
12945 if ((width*10) / 10 != width) {
12946 PyErr_SetString(PyExc_ValueError,
12947 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000012948 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000012949 }
12950 width = width*10 + (c - '0');
12951 }
12952 }
12953 if (c == '.') {
12954 prec = 0;
12955 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012957 if (c == '*') {
12958 v = getnextarg(args, arglen, &argidx);
12959 if (v == NULL)
12960 goto onError;
12961 if (!PyLong_Check(v)) {
12962 PyErr_SetString(PyExc_TypeError,
12963 "* wants int");
12964 goto onError;
12965 }
12966 prec = PyLong_AsLong(v);
12967 if (prec == -1 && PyErr_Occurred())
12968 goto onError;
12969 if (prec < 0)
12970 prec = 0;
12971 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012973 }
12974 else if (c >= '0' && c <= '9') {
12975 prec = c - '0';
12976 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012978 if (c < '0' || c > '9')
12979 break;
12980 if ((prec*10) / 10 != prec) {
12981 PyErr_SetString(PyExc_ValueError,
12982 "prec too big");
12983 goto onError;
12984 }
12985 prec = prec*10 + (c - '0');
12986 }
12987 }
12988 } /* prec */
12989 if (fmtcnt >= 0) {
12990 if (c == 'h' || c == 'l' || c == 'L') {
12991 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000012993 }
12994 }
12995 if (fmtcnt < 0) {
12996 PyErr_SetString(PyExc_ValueError,
12997 "incomplete format");
12998 goto onError;
12999 }
13000 if (c != '%') {
13001 v = getnextarg(args, arglen, &argidx);
13002 if (v == NULL)
13003 goto onError;
13004 }
13005 sign = 0;
13006 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013007 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 switch (c) {
13009
13010 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013011 _PyAccu_Accumulate(&acc, percent);
13012 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013013
13014 case 's':
13015 case 'r':
13016 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013017 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013018 temp = v;
13019 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013020 }
13021 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013022 if (c == 's')
13023 temp = PyObject_Str(v);
13024 else if (c == 'r')
13025 temp = PyObject_Repr(v);
13026 else
13027 temp = PyObject_ASCII(v);
13028 if (temp == NULL)
13029 goto onError;
13030 if (PyUnicode_Check(temp))
13031 /* nothing to do */;
13032 else {
13033 Py_DECREF(temp);
13034 PyErr_SetString(PyExc_TypeError,
13035 "%s argument has non-string str()");
13036 goto onError;
13037 }
13038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 if (PyUnicode_READY(temp) == -1) {
13040 Py_CLEAR(temp);
13041 goto onError;
13042 }
13043 pbuf = PyUnicode_DATA(temp);
13044 kind = PyUnicode_KIND(temp);
13045 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013046 if (prec >= 0 && len > prec)
13047 len = prec;
13048 break;
13049
13050 case 'i':
13051 case 'd':
13052 case 'u':
13053 case 'o':
13054 case 'x':
13055 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013056 isnumok = 0;
13057 if (PyNumber_Check(v)) {
13058 PyObject *iobj=NULL;
13059
13060 if (PyLong_Check(v)) {
13061 iobj = v;
13062 Py_INCREF(iobj);
13063 }
13064 else {
13065 iobj = PyNumber_Long(v);
13066 }
13067 if (iobj!=NULL) {
13068 if (PyLong_Check(iobj)) {
13069 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013070 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013071 Py_DECREF(iobj);
13072 if (!temp)
13073 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013074 if (PyUnicode_READY(temp) == -1) {
13075 Py_CLEAR(temp);
13076 goto onError;
13077 }
13078 pbuf = PyUnicode_DATA(temp);
13079 kind = PyUnicode_KIND(temp);
13080 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 sign = 1;
13082 }
13083 else {
13084 Py_DECREF(iobj);
13085 }
13086 }
13087 }
13088 if (!isnumok) {
13089 PyErr_Format(PyExc_TypeError,
13090 "%%%c format: a number is required, "
13091 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13092 goto onError;
13093 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013094 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013096 fillobj = zero;
13097 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013098 break;
13099
13100 case 'e':
13101 case 'E':
13102 case 'f':
13103 case 'F':
13104 case 'g':
13105 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013106 temp = formatfloat(v, flags, prec, c);
13107 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013109 if (PyUnicode_READY(temp) == -1) {
13110 Py_CLEAR(temp);
13111 goto onError;
13112 }
13113 pbuf = PyUnicode_DATA(temp);
13114 kind = PyUnicode_KIND(temp);
13115 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013116 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013117 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013118 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013119 fillobj = zero;
13120 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013121 break;
13122
13123 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013124 {
13125 Py_UCS4 ch = formatchar(v);
13126 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013127 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013128 temp = _PyUnicode_FromUCS4(&ch, 1);
13129 if (temp == NULL)
13130 goto onError;
13131 pbuf = PyUnicode_DATA(temp);
13132 kind = PyUnicode_KIND(temp);
13133 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013134 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013135 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013136
13137 default:
13138 PyErr_Format(PyExc_ValueError,
13139 "unsupported format character '%c' (0x%x) "
13140 "at index %zd",
13141 (31<=c && c<=126) ? (char)c : '?',
13142 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013144 goto onError;
13145 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013146 /* pbuf is initialized here. */
13147 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013148 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013149 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13150 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013151 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013152 pindex++;
13153 }
13154 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13155 signobj = plus;
13156 len--;
13157 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 }
13159 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013160 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013161 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013162 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 else
13164 sign = 0;
13165 }
13166 if (width < len)
13167 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013168 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013169 if (fill != ' ') {
13170 assert(signobj != NULL);
13171 if (_PyAccu_Accumulate(&acc, signobj))
13172 goto onError;
13173 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 if (width > len)
13175 width--;
13176 }
13177 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013178 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013179 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013181 second = get_latin1_char(
13182 PyUnicode_READ(kind, pbuf, pindex + 1));
13183 pindex += 2;
13184 if (second == NULL ||
13185 _PyAccu_Accumulate(&acc, zero) ||
13186 _PyAccu_Accumulate(&acc, second))
13187 goto onError;
13188 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013189 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013190 width -= 2;
13191 if (width < 0)
13192 width = 0;
13193 len -= 2;
13194 }
13195 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013196 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013197 if (repeat_accumulate(&acc, fillobj, width - len))
13198 goto onError;
13199 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 }
13201 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013202 if (sign) {
13203 assert(signobj != NULL);
13204 if (_PyAccu_Accumulate(&acc, signobj))
13205 goto onError;
13206 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013208 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13209 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013210 second = get_latin1_char(
13211 PyUnicode_READ(kind, pbuf, pindex + 1));
13212 pindex += 2;
13213 if (second == NULL ||
13214 _PyAccu_Accumulate(&acc, zero) ||
13215 _PyAccu_Accumulate(&acc, second))
13216 goto onError;
13217 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013218 }
13219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013220 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013221 if (temp != NULL) {
13222 assert(pbuf == PyUnicode_DATA(temp));
13223 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013224 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013225 else {
13226 const char *p = (const char *) pbuf;
13227 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013228 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013229 v = PyUnicode_FromKindAndData(kind, p, len);
13230 }
13231 if (v == NULL)
13232 goto onError;
13233 r = _PyAccu_Accumulate(&acc, v);
13234 Py_DECREF(v);
13235 if (r)
13236 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013237 if (width > len && repeat_accumulate(&acc, blank, width - len))
13238 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 if (dict && (argidx < arglen) && c != '%') {
13240 PyErr_SetString(PyExc_TypeError,
13241 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013242 goto onError;
13243 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013246 } /* until end */
13247 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 PyErr_SetString(PyExc_TypeError,
13249 "not all arguments converted during string formatting");
13250 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251 }
13252
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013253 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013254 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256 }
13257 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013258 Py_XDECREF(temp);
13259 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260 return (PyObject *)result;
13261
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013263 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013264 Py_XDECREF(temp);
13265 Py_XDECREF(second);
13266 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013268 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013269 }
13270 return NULL;
13271}
13272
Jeremy Hylton938ace62002-07-17 16:30:39 +000013273static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013274unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13275
Tim Peters6d6c1a32001-08-02 04:15:00 +000013276static PyObject *
13277unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13278{
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013280 static char *kwlist[] = {"object", "encoding", "errors", 0};
13281 char *encoding = NULL;
13282 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013283
Benjamin Peterson14339b62009-01-31 16:36:08 +000013284 if (type != &PyUnicode_Type)
13285 return unicode_subtype_new(type, args, kwds);
13286 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013288 return NULL;
13289 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013290 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013291 if (encoding == NULL && errors == NULL)
13292 return PyObject_Str(x);
13293 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013295}
13296
Guido van Rossume023fe02001-08-30 03:12:59 +000013297static PyObject *
13298unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13299{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013300 PyUnicodeObject *unicode, *self;
13301 Py_ssize_t length, char_size;
13302 int share_wstr, share_utf8;
13303 unsigned int kind;
13304 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013305
Benjamin Peterson14339b62009-01-31 16:36:08 +000013306 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013307
13308 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13309 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013310 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013311 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013312 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013313 return NULL;
13314
13315 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13316 if (self == NULL) {
13317 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013318 return NULL;
13319 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013320 kind = PyUnicode_KIND(unicode);
13321 length = PyUnicode_GET_LENGTH(unicode);
13322
13323 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013324#ifdef Py_DEBUG
13325 _PyUnicode_HASH(self) = -1;
13326#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013327 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013328#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013329 _PyUnicode_STATE(self).interned = 0;
13330 _PyUnicode_STATE(self).kind = kind;
13331 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013332 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013333 _PyUnicode_STATE(self).ready = 1;
13334 _PyUnicode_WSTR(self) = NULL;
13335 _PyUnicode_UTF8_LENGTH(self) = 0;
13336 _PyUnicode_UTF8(self) = NULL;
13337 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013338 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013339
13340 share_utf8 = 0;
13341 share_wstr = 0;
13342 if (kind == PyUnicode_1BYTE_KIND) {
13343 char_size = 1;
13344 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13345 share_utf8 = 1;
13346 }
13347 else if (kind == PyUnicode_2BYTE_KIND) {
13348 char_size = 2;
13349 if (sizeof(wchar_t) == 2)
13350 share_wstr = 1;
13351 }
13352 else {
13353 assert(kind == PyUnicode_4BYTE_KIND);
13354 char_size = 4;
13355 if (sizeof(wchar_t) == 4)
13356 share_wstr = 1;
13357 }
13358
13359 /* Ensure we won't overflow the length. */
13360 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13361 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013362 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013363 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013364 data = PyObject_MALLOC((length + 1) * char_size);
13365 if (data == NULL) {
13366 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013367 goto onError;
13368 }
13369
Victor Stinnerc3c74152011-10-02 20:39:55 +020013370 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013371 if (share_utf8) {
13372 _PyUnicode_UTF8_LENGTH(self) = length;
13373 _PyUnicode_UTF8(self) = data;
13374 }
13375 if (share_wstr) {
13376 _PyUnicode_WSTR_LENGTH(self) = length;
13377 _PyUnicode_WSTR(self) = (wchar_t *)data;
13378 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013380 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013381 kind * (length + 1));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013382 Py_DECREF(unicode);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013383 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013384#ifdef Py_DEBUG
13385 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13386#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013387 return (PyObject *)self;
13388
13389onError:
13390 Py_DECREF(unicode);
13391 Py_DECREF(self);
13392 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013393}
13394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013395PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013397\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013398Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013399encoding defaults to the current default string encoding.\n\
13400errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013401
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013402static PyObject *unicode_iter(PyObject *seq);
13403
Guido van Rossumd57fd912000-03-10 22:53:23 +000013404PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013406 "str", /* tp_name */
13407 sizeof(PyUnicodeObject), /* tp_size */
13408 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013409 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013410 (destructor)unicode_dealloc, /* tp_dealloc */
13411 0, /* tp_print */
13412 0, /* tp_getattr */
13413 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013414 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013415 unicode_repr, /* tp_repr */
13416 &unicode_as_number, /* tp_as_number */
13417 &unicode_as_sequence, /* tp_as_sequence */
13418 &unicode_as_mapping, /* tp_as_mapping */
13419 (hashfunc) unicode_hash, /* tp_hash*/
13420 0, /* tp_call*/
13421 (reprfunc) unicode_str, /* tp_str */
13422 PyObject_GenericGetAttr, /* tp_getattro */
13423 0, /* tp_setattro */
13424 0, /* tp_as_buffer */
13425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013427 unicode_doc, /* tp_doc */
13428 0, /* tp_traverse */
13429 0, /* tp_clear */
13430 PyUnicode_RichCompare, /* tp_richcompare */
13431 0, /* tp_weaklistoffset */
13432 unicode_iter, /* tp_iter */
13433 0, /* tp_iternext */
13434 unicode_methods, /* tp_methods */
13435 0, /* tp_members */
13436 0, /* tp_getset */
13437 &PyBaseObject_Type, /* tp_base */
13438 0, /* tp_dict */
13439 0, /* tp_descr_get */
13440 0, /* tp_descr_set */
13441 0, /* tp_dictoffset */
13442 0, /* tp_init */
13443 0, /* tp_alloc */
13444 unicode_new, /* tp_new */
13445 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013446};
13447
13448/* Initialize the Unicode implementation */
13449
Thomas Wouters78890102000-07-22 19:25:51 +000013450void _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013451{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013452 int i;
13453
Thomas Wouters477c8d52006-05-27 19:21:47 +000013454 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013455 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013456 0x000A, /* LINE FEED */
13457 0x000D, /* CARRIAGE RETURN */
13458 0x001C, /* FILE SEPARATOR */
13459 0x001D, /* GROUP SEPARATOR */
13460 0x001E, /* RECORD SEPARATOR */
13461 0x0085, /* NEXT LINE */
13462 0x2028, /* LINE SEPARATOR */
13463 0x2029, /* PARAGRAPH SEPARATOR */
13464 };
13465
Fred Drakee4315f52000-05-09 19:53:39 +000013466 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013467 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013468 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013469 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013470 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013471
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013472 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013473 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013474 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013476
13477 /* initialize the linebreak bloom filter */
13478 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013479 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013480 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013481
13482 PyType_Ready(&EncodingMapType);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013483}
13484
13485/* Finalize the Unicode implementation */
13486
Christian Heimesa156e092008-02-16 07:38:31 +000013487int
13488PyUnicode_ClearFreeList(void)
13489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013491}
13492
Guido van Rossumd57fd912000-03-10 22:53:23 +000013493void
Thomas Wouters78890102000-07-22 19:25:51 +000013494_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013495{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013496 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013498 Py_XDECREF(unicode_empty);
13499 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013500
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013501 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 if (unicode_latin1[i]) {
13503 Py_DECREF(unicode_latin1[i]);
13504 unicode_latin1[i] = NULL;
13505 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013506 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013507 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013508 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013509}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013510
Walter Dörwald16807132007-05-25 13:52:07 +000013511void
13512PyUnicode_InternInPlace(PyObject **p)
13513{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013514 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13515 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013516#ifdef Py_DEBUG
13517 assert(s != NULL);
13518 assert(_PyUnicode_CHECK(s));
13519#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013520 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013521 return;
13522#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013523 /* If it's a subclass, we don't really know what putting
13524 it in the interned dict might do. */
13525 if (!PyUnicode_CheckExact(s))
13526 return;
13527 if (PyUnicode_CHECK_INTERNED(s))
13528 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013529 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013530 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013531 return;
13532 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013533 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013534 if (interned == NULL) {
13535 interned = PyDict_New();
13536 if (interned == NULL) {
13537 PyErr_Clear(); /* Don't leave an exception */
13538 return;
13539 }
13540 }
13541 /* It might be that the GetItem call fails even
13542 though the key is present in the dictionary,
13543 namely when this happens during a stack overflow. */
13544 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013546 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013547
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 if (t) {
13549 Py_INCREF(t);
13550 Py_DECREF(*p);
13551 *p = t;
13552 return;
13553 }
Walter Dörwald16807132007-05-25 13:52:07 +000013554
Benjamin Peterson14339b62009-01-31 16:36:08 +000013555 PyThreadState_GET()->recursion_critical = 1;
13556 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13557 PyErr_Clear();
13558 PyThreadState_GET()->recursion_critical = 0;
13559 return;
13560 }
13561 PyThreadState_GET()->recursion_critical = 0;
13562 /* The two references in interned are not counted by refcnt.
13563 The deallocator will take care of this */
13564 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013565 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013566}
13567
13568void
13569PyUnicode_InternImmortal(PyObject **p)
13570{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013571 PyUnicodeObject *u = (PyUnicodeObject *)*p;
13572
Benjamin Peterson14339b62009-01-31 16:36:08 +000013573 PyUnicode_InternInPlace(p);
13574 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013575 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013576 Py_INCREF(*p);
13577 }
Walter Dörwald16807132007-05-25 13:52:07 +000013578}
13579
13580PyObject *
13581PyUnicode_InternFromString(const char *cp)
13582{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013583 PyObject *s = PyUnicode_FromString(cp);
13584 if (s == NULL)
13585 return NULL;
13586 PyUnicode_InternInPlace(&s);
13587 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013588}
13589
Alexander Belopolsky40018472011-02-26 01:02:56 +000013590void
13591_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013592{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013593 PyObject *keys;
13594 PyUnicodeObject *s;
13595 Py_ssize_t i, n;
13596 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013597
Benjamin Peterson14339b62009-01-31 16:36:08 +000013598 if (interned == NULL || !PyDict_Check(interned))
13599 return;
13600 keys = PyDict_Keys(interned);
13601 if (keys == NULL || !PyList_Check(keys)) {
13602 PyErr_Clear();
13603 return;
13604 }
Walter Dörwald16807132007-05-25 13:52:07 +000013605
Benjamin Peterson14339b62009-01-31 16:36:08 +000013606 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13607 detector, interned unicode strings are not forcibly deallocated;
13608 rather, we give them their stolen references back, and then clear
13609 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013610
Benjamin Peterson14339b62009-01-31 16:36:08 +000013611 n = PyList_GET_SIZE(keys);
13612 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013614 for (i = 0; i < n; i++) {
13615 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013616 if (PyUnicode_READY(s) == -1) {
13617 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013621 case SSTATE_NOT_INTERNED:
13622 /* XXX Shouldn't happen */
13623 break;
13624 case SSTATE_INTERNED_IMMORTAL:
13625 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013626 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013627 break;
13628 case SSTATE_INTERNED_MORTAL:
13629 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013631 break;
13632 default:
13633 Py_FatalError("Inconsistent interned string state.");
13634 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013636 }
13637 fprintf(stderr, "total size of all interned strings: "
13638 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13639 "mortal/immortal\n", mortal_size, immortal_size);
13640 Py_DECREF(keys);
13641 PyDict_Clear(interned);
13642 Py_DECREF(interned);
13643 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013644}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013645
13646
13647/********************* Unicode Iterator **************************/
13648
13649typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013650 PyObject_HEAD
13651 Py_ssize_t it_index;
13652 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013653} unicodeiterobject;
13654
13655static void
13656unicodeiter_dealloc(unicodeiterobject *it)
13657{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013658 _PyObject_GC_UNTRACK(it);
13659 Py_XDECREF(it->it_seq);
13660 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013661}
13662
13663static int
13664unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
13665{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013666 Py_VISIT(it->it_seq);
13667 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013668}
13669
13670static PyObject *
13671unicodeiter_next(unicodeiterobject *it)
13672{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013673 PyUnicodeObject *seq;
13674 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013675
Benjamin Peterson14339b62009-01-31 16:36:08 +000013676 assert(it != NULL);
13677 seq = it->it_seq;
13678 if (seq == NULL)
13679 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013680 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013682 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
13683 int kind = PyUnicode_KIND(seq);
13684 void *data = PyUnicode_DATA(seq);
13685 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
13686 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013687 if (item != NULL)
13688 ++it->it_index;
13689 return item;
13690 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013691
Benjamin Peterson14339b62009-01-31 16:36:08 +000013692 Py_DECREF(seq);
13693 it->it_seq = NULL;
13694 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013695}
13696
13697static PyObject *
13698unicodeiter_len(unicodeiterobject *it)
13699{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013700 Py_ssize_t len = 0;
13701 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013702 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013703 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013704}
13705
13706PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
13707
13708static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013709 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000013710 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000013711 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013712};
13713
13714PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013715 PyVarObject_HEAD_INIT(&PyType_Type, 0)
13716 "str_iterator", /* tp_name */
13717 sizeof(unicodeiterobject), /* tp_basicsize */
13718 0, /* tp_itemsize */
13719 /* methods */
13720 (destructor)unicodeiter_dealloc, /* tp_dealloc */
13721 0, /* tp_print */
13722 0, /* tp_getattr */
13723 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013724 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013725 0, /* tp_repr */
13726 0, /* tp_as_number */
13727 0, /* tp_as_sequence */
13728 0, /* tp_as_mapping */
13729 0, /* tp_hash */
13730 0, /* tp_call */
13731 0, /* tp_str */
13732 PyObject_GenericGetAttr, /* tp_getattro */
13733 0, /* tp_setattro */
13734 0, /* tp_as_buffer */
13735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
13736 0, /* tp_doc */
13737 (traverseproc)unicodeiter_traverse, /* tp_traverse */
13738 0, /* tp_clear */
13739 0, /* tp_richcompare */
13740 0, /* tp_weaklistoffset */
13741 PyObject_SelfIter, /* tp_iter */
13742 (iternextfunc)unicodeiter_next, /* tp_iternext */
13743 unicodeiter_methods, /* tp_methods */
13744 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013745};
13746
13747static PyObject *
13748unicode_iter(PyObject *seq)
13749{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013751
Benjamin Peterson14339b62009-01-31 16:36:08 +000013752 if (!PyUnicode_Check(seq)) {
13753 PyErr_BadInternalCall();
13754 return NULL;
13755 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013756 if (PyUnicode_READY(seq) == -1)
13757 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013758 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
13759 if (it == NULL)
13760 return NULL;
13761 it->it_index = 0;
13762 Py_INCREF(seq);
13763 it->it_seq = (PyUnicodeObject *)seq;
13764 _PyObject_GC_TRACK(it);
13765 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013766}
13767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013768#define UNIOP(x) Py_UNICODE_##x
13769#define UNIOP_t Py_UNICODE
13770#include "uniops.h"
13771#undef UNIOP
13772#undef UNIOP_t
13773#define UNIOP(x) Py_UCS4_##x
13774#define UNIOP_t Py_UCS4
13775#include "uniops.h"
13776#undef UNIOP
13777#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000013778
Victor Stinner71133ff2010-09-01 23:43:53 +000013779Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000013780PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000013781{
13782 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
Victor Stinner577db2c2011-10-11 22:12:48 +020013783 Py_UNICODE *u, *copy;
Victor Stinner71133ff2010-09-01 23:43:53 +000013784 Py_ssize_t size;
13785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013786 if (!PyUnicode_Check(unicode)) {
13787 PyErr_BadArgument();
13788 return NULL;
13789 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013790 u = PyUnicode_AsUnicode(object);
13791 if (u == NULL)
13792 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000013793 /* Ensure we won't overflow the size. */
13794 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
13795 PyErr_NoMemory();
13796 return NULL;
13797 }
13798 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
13799 size *= sizeof(Py_UNICODE);
13800 copy = PyMem_Malloc(size);
13801 if (copy == NULL) {
13802 PyErr_NoMemory();
13803 return NULL;
13804 }
Victor Stinner577db2c2011-10-11 22:12:48 +020013805 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000013806 return copy;
13807}
Martin v. Löwis5b222132007-06-10 09:51:05 +000013808
Georg Brandl66c221e2010-10-14 07:04:07 +000013809/* A _string module, to export formatter_parser and formatter_field_name_split
13810 to the string.Formatter class implemented in Python. */
13811
13812static PyMethodDef _string_methods[] = {
13813 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
13814 METH_O, PyDoc_STR("split the argument as a field name")},
13815 {"formatter_parser", (PyCFunction) formatter_parser,
13816 METH_O, PyDoc_STR("parse the argument as a format string")},
13817 {NULL, NULL}
13818};
13819
13820static struct PyModuleDef _string_module = {
13821 PyModuleDef_HEAD_INIT,
13822 "_string",
13823 PyDoc_STR("string helper module"),
13824 0,
13825 _string_methods,
13826 NULL,
13827 NULL,
13828 NULL,
13829 NULL
13830};
13831
13832PyMODINIT_FUNC
13833PyInit__string(void)
13834{
13835 return PyModule_Create(&_string_module);
13836}
13837
13838
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013839#ifdef __cplusplus
13840}
13841#endif