blob: 3bf19328bc57d75e8bf35ba60526ea45e91f49fd [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"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Larry Hastings61272b72014-01-07 12:41:53 -080050/*[clinic input]
Larry Hastingsc2047262014-01-25 20:43:29 -080051class str "PyUnicodeObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080052[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080053/*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080054
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000055/* --- Globals ------------------------------------------------------------
56
Serhiy Storchaka05997252013-01-26 12:14:02 +020057NOTE: In the interpreter's initialization phase, some globals are currently
58 initialized dynamically as needed. In the process Unicode objects may
59 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000060
61*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000062
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063
64#ifdef __cplusplus
65extern "C" {
66#endif
67
Victor Stinner8faf8212011-12-08 22:14:11 +010068/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
69#define MAX_UNICODE 0x10ffff
70
Victor Stinner910337b2011-10-03 03:20:16 +020071#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020072# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020073#else
74# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
75#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020076
Victor Stinnere90fe6a2011-10-01 16:48:13 +020077#define _PyUnicode_UTF8(op) \
78 (((PyCompactUnicodeObject*)(op))->utf8)
79#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020080 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020081 assert(PyUnicode_IS_READY(op)), \
82 PyUnicode_IS_COMPACT_ASCII(op) ? \
83 ((char*)((PyASCIIObject*)(op) + 1)) : \
84 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020085#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020086 (((PyCompactUnicodeObject*)(op))->utf8_length)
87#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020088 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020089 assert(PyUnicode_IS_READY(op)), \
90 PyUnicode_IS_COMPACT_ASCII(op) ? \
91 ((PyASCIIObject*)(op))->length : \
92 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020093#define _PyUnicode_WSTR(op) \
94 (((PyASCIIObject*)(op))->wstr)
95#define _PyUnicode_WSTR_LENGTH(op) \
96 (((PyCompactUnicodeObject*)(op))->wstr_length)
97#define _PyUnicode_LENGTH(op) \
98 (((PyASCIIObject *)(op))->length)
99#define _PyUnicode_STATE(op) \
100 (((PyASCIIObject *)(op))->state)
101#define _PyUnicode_HASH(op) \
102 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200103#define _PyUnicode_KIND(op) \
104 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200105 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200106#define _PyUnicode_GET_LENGTH(op) \
107 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200108 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200109#define _PyUnicode_DATA_ANY(op) \
110 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200111
Victor Stinner910337b2011-10-03 03:20:16 +0200112#undef PyUnicode_READY
113#define PyUnicode_READY(op) \
114 (assert(_PyUnicode_CHECK(op)), \
115 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200116 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100117 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200118
Victor Stinnerc379ead2011-10-03 12:52:27 +0200119#define _PyUnicode_SHARE_UTF8(op) \
120 (assert(_PyUnicode_CHECK(op)), \
121 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
122 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
123#define _PyUnicode_SHARE_WSTR(op) \
124 (assert(_PyUnicode_CHECK(op)), \
125 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
126
Victor Stinner829c0ad2011-10-03 01:08:02 +0200127/* true if the Unicode object has an allocated UTF-8 memory block
128 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200130 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200131 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200132 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
133
Victor Stinner03490912011-10-03 23:45:12 +0200134/* true if the Unicode object has an allocated wstr memory block
135 (not shared with other data) */
136#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200137 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200138 (!PyUnicode_IS_READY(op) || \
139 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
140
Victor Stinner910337b2011-10-03 03:20:16 +0200141/* Generic helper macro to convert characters of different types.
142 from_type and to_type have to be valid type names, begin and end
143 are pointers to the source characters which should be of type
144 "from_type *". to is a pointer of type "to_type *" and points to the
145 buffer where the result characters are written to. */
146#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
147 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100148 to_type *_to = (to_type *)(to); \
149 const from_type *_iter = (from_type *)(begin); \
150 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200151 Py_ssize_t n = (_end) - (_iter); \
152 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200153 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200154 while (_iter < (_unrolled_end)) { \
155 _to[0] = (to_type) _iter[0]; \
156 _to[1] = (to_type) _iter[1]; \
157 _to[2] = (to_type) _iter[2]; \
158 _to[3] = (to_type) _iter[3]; \
159 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200160 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200161 while (_iter < (_end)) \
162 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200163 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200164
Walter Dörwald16807132007-05-25 13:52:07 +0000165/* This dictionary holds all interned unicode strings. Note that references
166 to strings in this dictionary are *not* counted in the string's ob_refcnt.
167 When the interned string reaches a refcnt of 0 the string deallocation
168 function will delete the reference from this dictionary.
169
170 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000171 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000172*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200173static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000174
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000175/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200176static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200177
Serhiy Storchaka678db842013-01-26 12:16:36 +0200178#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200179 do { \
180 if (unicode_empty != NULL) \
181 Py_INCREF(unicode_empty); \
182 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200183 unicode_empty = PyUnicode_New(0, 0); \
184 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200185 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200186 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
187 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000190
Serhiy Storchaka678db842013-01-26 12:16:36 +0200191#define _Py_RETURN_UNICODE_EMPTY() \
192 do { \
193 _Py_INCREF_UNICODE_EMPTY(); \
194 return unicode_empty; \
195 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200197/* Forward declaration */
198Py_LOCAL_INLINE(int)
199_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
200
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200201/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200203
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000204/* Single character Unicode strings in the Latin-1 range are being
205 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200206static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000207
Christian Heimes190d79e2008-01-30 11:58:22 +0000208/* Fast detection of the most frequent whitespace characters */
209const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000211/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000213/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000214/* case 0x000C: * FORM FEED */
215/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000216 0, 1, 1, 1, 1, 1, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000218/* case 0x001C: * FILE SEPARATOR */
219/* case 0x001D: * GROUP SEPARATOR */
220/* case 0x001E: * RECORD SEPARATOR */
221/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000222 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000223/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000224 1, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000228
Benjamin Peterson14339b62009-01-31 16:36:08 +0000229 0, 0, 0, 0, 0, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0,
236 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000237};
238
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200239/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200240static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200241static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100242static int unicode_modifiable(PyObject *unicode);
243
Victor Stinnerfe226c02011-10-03 03:52:20 +0200244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100246_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200247static PyObject *
248_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
249static PyObject *
250_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
251
252static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000253unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000254 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100255 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000256 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
257
Alexander Belopolsky40018472011-02-26 01:02:56 +0000258static void
259raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300260 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100261 PyObject *unicode,
262 Py_ssize_t startpos, Py_ssize_t endpos,
263 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000264
Christian Heimes190d79e2008-01-30 11:58:22 +0000265/* Same for linebreaks */
266static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000267 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000268/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* 0x000B, * LINE TABULATION */
270/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000271/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000274/* 0x001C, * FILE SEPARATOR */
275/* 0x001D, * GROUP SEPARATOR */
276/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 0, 0, 0, 1, 1, 1, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000282
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 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
Christian Heimes190d79e2008-01-30 11:58:22 +0000291};
292
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300293/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
294 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000295Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000296PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000298#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 /* This is actually an illegal character, so it should
302 not be passed to unichr. */
303 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000304#endif
305}
306
Victor Stinner910337b2011-10-03 03:20:16 +0200307#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200308int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100309_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200310{
311 PyASCIIObject *ascii;
312 unsigned int kind;
313
314 assert(PyUnicode_Check(op));
315
316 ascii = (PyASCIIObject *)op;
317 kind = ascii->state.kind;
318
Victor Stinnera3b334d2011-10-03 13:53:37 +0200319 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200321 assert(ascii->state.ready == 1);
322 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200324 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200325 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200326
Victor Stinnera41463c2011-10-04 01:05:08 +0200327 if (ascii->state.compact == 1) {
328 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(kind == PyUnicode_1BYTE_KIND
330 || kind == PyUnicode_2BYTE_KIND
331 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200332 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200333 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100335 }
336 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
338
339 data = unicode->data.any;
340 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100341 assert(ascii->length == 0);
342 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100346 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200347 assert(ascii->wstr != NULL);
348 assert(data == NULL);
349 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200391 void *data;
392 Py_UCS4 ch;
393
394 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200395 for (i=0; i < ascii->length; i++)
396 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200397 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 if (ch > maxchar)
399 maxchar = ch;
400 }
401 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100402 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 255);
405 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 else
407 assert(maxchar < 128);
408 }
Victor Stinner77faf692011-11-20 18:56:05 +0100409 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100411 assert(maxchar <= 0xFFFF);
412 }
413 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200414 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100415 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100416 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200417 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200418 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400419 return 1;
420}
Victor Stinner910337b2011-10-03 03:20:16 +0200421#endif
422
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100423static PyObject*
424unicode_result_wchar(PyObject *unicode)
425{
426#ifndef Py_DEBUG
427 Py_ssize_t len;
428
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100429 len = _PyUnicode_WSTR_LENGTH(unicode);
430 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100431 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200432 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100433 }
434
435 if (len == 1) {
436 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100437 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100438 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
439 Py_DECREF(unicode);
440 return latin1_char;
441 }
442 }
443
444 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200445 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100446 return NULL;
447 }
448#else
Victor Stinneraa771272012-10-04 02:32:58 +0200449 assert(Py_REFCNT(unicode) == 1);
450
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100451 /* don't make the result ready in debug mode to ensure that the caller
452 makes the string ready before using it */
453 assert(_PyUnicode_CheckConsistency(unicode, 1));
454#endif
455 return unicode;
456}
457
458static PyObject*
459unicode_result_ready(PyObject *unicode)
460{
461 Py_ssize_t length;
462
463 length = PyUnicode_GET_LENGTH(unicode);
464 if (length == 0) {
465 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100466 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200467 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100468 }
469 return unicode_empty;
470 }
471
472 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200473 void *data = PyUnicode_DATA(unicode);
474 int kind = PyUnicode_KIND(unicode);
475 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100476 if (ch < 256) {
477 PyObject *latin1_char = unicode_latin1[ch];
478 if (latin1_char != NULL) {
479 if (unicode != latin1_char) {
480 Py_INCREF(latin1_char);
481 Py_DECREF(unicode);
482 }
483 return latin1_char;
484 }
485 else {
486 assert(_PyUnicode_CheckConsistency(unicode, 1));
487 Py_INCREF(unicode);
488 unicode_latin1[ch] = unicode;
489 return unicode;
490 }
491 }
492 }
493
494 assert(_PyUnicode_CheckConsistency(unicode, 1));
495 return unicode;
496}
497
498static PyObject*
499unicode_result(PyObject *unicode)
500{
501 assert(_PyUnicode_CHECK(unicode));
502 if (PyUnicode_IS_READY(unicode))
503 return unicode_result_ready(unicode);
504 else
505 return unicode_result_wchar(unicode);
506}
507
Victor Stinnerc4b49542011-12-11 22:44:26 +0100508static PyObject*
509unicode_result_unchanged(PyObject *unicode)
510{
511 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500512 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100513 return NULL;
514 Py_INCREF(unicode);
515 return unicode;
516 }
517 else
518 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100519 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100520}
521
Victor Stinner3a50e702011-10-18 21:21:00 +0200522#ifdef HAVE_MBCS
523static OSVERSIONINFOEX winver;
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526/* --- Bloom Filters ----------------------------------------------------- */
527
528/* stuff to implement simple "bloom filters" for Unicode characters.
529 to keep things simple, we use a single bitmask, using the least 5
530 bits from each unicode characters as the bit index. */
531
532/* the linebreak mask is set up by Unicode_Init below */
533
Antoine Pitrouf068f942010-01-13 14:19:12 +0000534#if LONG_BIT >= 128
535#define BLOOM_WIDTH 128
536#elif LONG_BIT >= 64
537#define BLOOM_WIDTH 64
538#elif LONG_BIT >= 32
539#define BLOOM_WIDTH 32
540#else
541#error "LONG_BIT is smaller than 32"
542#endif
543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544#define BLOOM_MASK unsigned long
545
Serhiy Storchaka05997252013-01-26 12:14:02 +0200546static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
Antoine Pitrouf068f942010-01-13 14:19:12 +0000548#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Benjamin Peterson29060642009-01-31 22:14:21 +0000550#define BLOOM_LINEBREAK(ch) \
551 ((ch) < 128U ? ascii_linebreak[(ch)] : \
552 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
Alexander Belopolsky40018472011-02-26 01:02:56 +0000554Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200555make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556{
Victor Stinnera85af502013-04-09 21:53:54 +0200557#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
558 do { \
559 TYPE *data = (TYPE *)PTR; \
560 TYPE *end = data + LEN; \
561 Py_UCS4 ch; \
562 for (; data != end; data++) { \
563 ch = *data; \
564 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
565 } \
566 break; \
567 } while (0)
568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 /* calculate simple bloom-style bitmask for a given unicode string */
570
Antoine Pitrouf068f942010-01-13 14:19:12 +0000571 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200574 switch (kind) {
575 case PyUnicode_1BYTE_KIND:
576 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
577 break;
578 case PyUnicode_2BYTE_KIND:
579 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
580 break;
581 case PyUnicode_4BYTE_KIND:
582 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
583 break;
584 default:
585 assert(0);
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200588
589#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590}
591
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200592/* Compilation of templated routines */
593
594#include "stringlib/asciilib.h"
595#include "stringlib/fastsearch.h"
596#include "stringlib/partition.h"
597#include "stringlib/split.h"
598#include "stringlib/count.h"
599#include "stringlib/find.h"
600#include "stringlib/find_max_char.h"
601#include "stringlib/localeutil.h"
602#include "stringlib/undef.h"
603
604#include "stringlib/ucs1lib.h"
605#include "stringlib/fastsearch.h"
606#include "stringlib/partition.h"
607#include "stringlib/split.h"
608#include "stringlib/count.h"
609#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300610#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200611#include "stringlib/find_max_char.h"
612#include "stringlib/localeutil.h"
613#include "stringlib/undef.h"
614
615#include "stringlib/ucs2lib.h"
616#include "stringlib/fastsearch.h"
617#include "stringlib/partition.h"
618#include "stringlib/split.h"
619#include "stringlib/count.h"
620#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300621#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622#include "stringlib/find_max_char.h"
623#include "stringlib/localeutil.h"
624#include "stringlib/undef.h"
625
626#include "stringlib/ucs4lib.h"
627#include "stringlib/fastsearch.h"
628#include "stringlib/partition.h"
629#include "stringlib/split.h"
630#include "stringlib/count.h"
631#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300632#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200633#include "stringlib/find_max_char.h"
634#include "stringlib/localeutil.h"
635#include "stringlib/undef.h"
636
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200637#include "stringlib/unicodedefs.h"
638#include "stringlib/fastsearch.h"
639#include "stringlib/count.h"
640#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100641#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200642
Guido van Rossumd57fd912000-03-10 22:53:23 +0000643/* --- Unicode Object ----------------------------------------------------- */
644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200645static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200646fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
649 Py_ssize_t size, Py_UCS4 ch,
650 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200651{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200652 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
653
654 switch (kind) {
655 case PyUnicode_1BYTE_KIND:
656 {
657 Py_UCS1 ch1 = (Py_UCS1) ch;
658 if (ch1 == ch)
659 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
660 else
661 return -1;
662 }
663 case PyUnicode_2BYTE_KIND:
664 {
665 Py_UCS2 ch2 = (Py_UCS2) ch;
666 if (ch2 == ch)
667 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
668 else
669 return -1;
670 }
671 case PyUnicode_4BYTE_KIND:
672 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
673 default:
674 assert(0);
675 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200676 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677}
678
Victor Stinnerafffce42012-10-03 23:03:17 +0200679#ifdef Py_DEBUG
680/* Fill the data of an Unicode string with invalid characters to detect bugs
681 earlier.
682
683 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
684 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
685 invalid character in Unicode 6.0. */
686static void
687unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
688{
689 int kind = PyUnicode_KIND(unicode);
690 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
691 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
692 if (length <= old_length)
693 return;
694 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
695}
696#endif
697
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698static PyObject*
699resize_compact(PyObject *unicode, Py_ssize_t length)
700{
701 Py_ssize_t char_size;
702 Py_ssize_t struct_size;
703 Py_ssize_t new_size;
704 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100705 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200706#ifdef Py_DEBUG
707 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
708#endif
709
Victor Stinner79891572012-05-03 13:43:07 +0200710 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200711 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100712 assert(PyUnicode_IS_COMPACT(unicode));
713
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200714 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100715 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716 struct_size = sizeof(PyASCIIObject);
717 else
718 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200719 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720
Victor Stinnerfe226c02011-10-03 03:52:20 +0200721 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
722 PyErr_NoMemory();
723 return NULL;
724 }
725 new_size = (struct_size + (length + 1) * char_size);
726
Victor Stinner84def372011-12-11 20:04:56 +0100727 _Py_DEC_REFTOTAL;
728 _Py_ForgetReference(unicode);
729
730 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
731 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100732 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 PyErr_NoMemory();
734 return NULL;
735 }
Victor Stinner84def372011-12-11 20:04:56 +0100736 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100738
Victor Stinnerfe226c02011-10-03 03:52:20 +0200739 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200740 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100742 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200743 _PyUnicode_WSTR_LENGTH(unicode) = length;
744 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100745 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
746 PyObject_DEL(_PyUnicode_WSTR(unicode));
747 _PyUnicode_WSTR(unicode) = NULL;
748 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200749#ifdef Py_DEBUG
750 unicode_fill_invalid(unicode, old_length);
751#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200752 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
753 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200754 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200755 return unicode;
756}
757
Alexander Belopolsky40018472011-02-26 01:02:56 +0000758static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200759resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000760{
Victor Stinner95663112011-10-04 01:03:50 +0200761 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100762 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200764 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000765
Victor Stinnerfe226c02011-10-03 03:52:20 +0200766 if (PyUnicode_IS_READY(unicode)) {
767 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200768 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200770#ifdef Py_DEBUG
771 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
772#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200773
774 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200775 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200776 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
777 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200778
779 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
780 PyErr_NoMemory();
781 return -1;
782 }
783 new_size = (length + 1) * char_size;
784
Victor Stinner7a9105a2011-12-12 00:13:42 +0100785 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
786 {
787 PyObject_DEL(_PyUnicode_UTF8(unicode));
788 _PyUnicode_UTF8(unicode) = NULL;
789 _PyUnicode_UTF8_LENGTH(unicode) = 0;
790 }
791
Victor Stinnerfe226c02011-10-03 03:52:20 +0200792 data = (PyObject *)PyObject_REALLOC(data, new_size);
793 if (data == NULL) {
794 PyErr_NoMemory();
795 return -1;
796 }
797 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200798 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_WSTR_LENGTH(unicode) = length;
801 }
802 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200803 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200804 _PyUnicode_UTF8_LENGTH(unicode) = length;
805 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200806 _PyUnicode_LENGTH(unicode) = length;
807 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200808#ifdef Py_DEBUG
809 unicode_fill_invalid(unicode, old_length);
810#endif
Victor Stinner95663112011-10-04 01:03:50 +0200811 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200812 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200814 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200815 }
Victor Stinner95663112011-10-04 01:03:50 +0200816 assert(_PyUnicode_WSTR(unicode) != NULL);
817
818 /* check for integer overflow */
819 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
820 PyErr_NoMemory();
821 return -1;
822 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100823 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200824 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100825 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200826 if (!wstr) {
827 PyErr_NoMemory();
828 return -1;
829 }
830 _PyUnicode_WSTR(unicode) = wstr;
831 _PyUnicode_WSTR(unicode)[length] = 0;
832 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200833 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000834 return 0;
835}
836
Victor Stinnerfe226c02011-10-03 03:52:20 +0200837static PyObject*
838resize_copy(PyObject *unicode, Py_ssize_t length)
839{
840 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100843
Benjamin Petersonbac79492012-01-14 13:34:47 -0500844 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100845 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200846
847 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
848 if (copy == NULL)
849 return NULL;
850
851 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200852 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200853 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200854 }
855 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200856 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100857
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200858 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200859 if (w == NULL)
860 return NULL;
861 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
862 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200863 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
864 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200865 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200866 }
867}
868
Guido van Rossumd57fd912000-03-10 22:53:23 +0000869/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000870 Ux0000 terminated; some code (e.g. new_identifier)
871 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000872
873 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000874 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000875
876*/
877
Alexander Belopolsky40018472011-02-26 01:02:56 +0000878static PyUnicodeObject *
879_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000880{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200881 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000883
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000885 if (length == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000888 }
889
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000890 /* Ensure we won't overflow the size. */
891 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
892 return (PyUnicodeObject *)PyErr_NoMemory();
893 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894 if (length < 0) {
895 PyErr_SetString(PyExc_SystemError,
896 "Negative size passed to _PyUnicode_New");
897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000898 }
899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200900 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
901 if (unicode == NULL)
902 return NULL;
903 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100904
905 _PyUnicode_WSTR_LENGTH(unicode) = length;
906 _PyUnicode_HASH(unicode) = -1;
907 _PyUnicode_STATE(unicode).interned = 0;
908 _PyUnicode_STATE(unicode).kind = 0;
909 _PyUnicode_STATE(unicode).compact = 0;
910 _PyUnicode_STATE(unicode).ready = 0;
911 _PyUnicode_STATE(unicode).ascii = 0;
912 _PyUnicode_DATA_ANY(unicode) = NULL;
913 _PyUnicode_LENGTH(unicode) = 0;
914 _PyUnicode_UTF8(unicode) = NULL;
915 _PyUnicode_UTF8_LENGTH(unicode) = 0;
916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200917 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
918 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100919 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000920 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100921 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000922 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200923
Jeremy Hyltond8082792003-09-16 19:41:39 +0000924 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000925 * the caller fails before initializing str -- unicode_resize()
926 * reads str[0], and the Keep-Alive optimization can keep memory
927 * allocated for str alive across a call to unicode_dealloc(unicode).
928 * We don't want unicode_resize to read uninitialized memory in
929 * that case.
930 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200931 _PyUnicode_WSTR(unicode)[0] = 0;
932 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100933
Victor Stinner7931d9a2011-11-04 00:22:48 +0100934 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000935 return unicode;
936}
937
Victor Stinnerf42dc442011-10-02 23:33:16 +0200938static const char*
939unicode_kind_name(PyObject *unicode)
940{
Victor Stinner42dfd712011-10-03 14:41:45 +0200941 /* don't check consistency: unicode_kind_name() is called from
942 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200943 if (!PyUnicode_IS_COMPACT(unicode))
944 {
945 if (!PyUnicode_IS_READY(unicode))
946 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600947 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200948 {
949 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200951 return "legacy ascii";
952 else
953 return "legacy latin1";
954 case PyUnicode_2BYTE_KIND:
955 return "legacy UCS2";
956 case PyUnicode_4BYTE_KIND:
957 return "legacy UCS4";
958 default:
959 return "<legacy invalid kind>";
960 }
961 }
962 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600963 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200964 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200965 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200966 return "ascii";
967 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200970 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200971 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200972 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 default:
974 return "<invalid compact kind>";
975 }
976}
977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979/* Functions wrapping macros for use in debugger */
980char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200981 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200982}
983
984void *_PyUnicode_compact_data(void *unicode) {
985 return _PyUnicode_COMPACT_DATA(unicode);
986}
987void *_PyUnicode_data(void *unicode){
988 printf("obj %p\n", unicode);
989 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
990 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
991 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
992 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
993 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
994 return PyUnicode_DATA(unicode);
995}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200996
997void
998_PyUnicode_Dump(PyObject *op)
999{
1000 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1002 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1003 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001004
Victor Stinnera849a4b2011-10-03 12:12:11 +02001005 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001006 {
1007 if (ascii->state.ascii)
1008 data = (ascii + 1);
1009 else
1010 data = (compact + 1);
1011 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001012 else
1013 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001014 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1015 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001016
Victor Stinnera849a4b2011-10-03 12:12:11 +02001017 if (ascii->wstr == data)
1018 printf("shared ");
1019 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001020
Victor Stinnera3b334d2011-10-03 13:53:37 +02001021 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001022 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001023 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1024 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001025 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1026 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001027 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001028 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001029}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001030#endif
1031
1032PyObject *
1033PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1034{
1035 PyObject *obj;
1036 PyCompactUnicodeObject *unicode;
1037 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001038 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001039 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001040 Py_ssize_t char_size;
1041 Py_ssize_t struct_size;
1042
1043 /* Optimization for empty strings */
1044 if (size == 0 && unicode_empty != NULL) {
1045 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001046 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 }
1048
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 is_ascii = 0;
1050 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051 struct_size = sizeof(PyCompactUnicodeObject);
1052 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001053 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 char_size = 1;
1055 is_ascii = 1;
1056 struct_size = sizeof(PyASCIIObject);
1057 }
1058 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001059 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 char_size = 1;
1061 }
1062 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001063 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 char_size = 2;
1065 if (sizeof(wchar_t) == 2)
1066 is_sharing = 1;
1067 }
1068 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001069 if (maxchar > MAX_UNICODE) {
1070 PyErr_SetString(PyExc_SystemError,
1071 "invalid maximum character passed to PyUnicode_New");
1072 return NULL;
1073 }
Victor Stinner8f825062012-04-27 13:55:39 +02001074 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075 char_size = 4;
1076 if (sizeof(wchar_t) == 4)
1077 is_sharing = 1;
1078 }
1079
1080 /* Ensure we won't overflow the size. */
1081 if (size < 0) {
1082 PyErr_SetString(PyExc_SystemError,
1083 "Negative size passed to PyUnicode_New");
1084 return NULL;
1085 }
1086 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1087 return PyErr_NoMemory();
1088
1089 /* Duplicated allocation code from _PyObject_New() instead of a call to
1090 * PyObject_New() so we are able to allocate space for the object and
1091 * it's data buffer.
1092 */
1093 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1094 if (obj == NULL)
1095 return PyErr_NoMemory();
1096 obj = PyObject_INIT(obj, &PyUnicode_Type);
1097 if (obj == NULL)
1098 return NULL;
1099
1100 unicode = (PyCompactUnicodeObject *)obj;
1101 if (is_ascii)
1102 data = ((PyASCIIObject*)obj) + 1;
1103 else
1104 data = unicode + 1;
1105 _PyUnicode_LENGTH(unicode) = size;
1106 _PyUnicode_HASH(unicode) = -1;
1107 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001108 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001109 _PyUnicode_STATE(unicode).compact = 1;
1110 _PyUnicode_STATE(unicode).ready = 1;
1111 _PyUnicode_STATE(unicode).ascii = is_ascii;
1112 if (is_ascii) {
1113 ((char*)data)[size] = 0;
1114 _PyUnicode_WSTR(unicode) = NULL;
1115 }
Victor Stinner8f825062012-04-27 13:55:39 +02001116 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001117 ((char*)data)[size] = 0;
1118 _PyUnicode_WSTR(unicode) = NULL;
1119 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001120 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001121 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001122 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 else {
1124 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001125 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001126 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001127 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001128 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001129 ((Py_UCS4*)data)[size] = 0;
1130 if (is_sharing) {
1131 _PyUnicode_WSTR_LENGTH(unicode) = size;
1132 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1133 }
1134 else {
1135 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1136 _PyUnicode_WSTR(unicode) = NULL;
1137 }
1138 }
Victor Stinner8f825062012-04-27 13:55:39 +02001139#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001140 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001141#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001142 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 return obj;
1144}
1145
1146#if SIZEOF_WCHAR_T == 2
1147/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1148 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001149 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150
1151 This function assumes that unicode can hold one more code point than wstr
1152 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001153static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001154unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001155 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156{
1157 const wchar_t *iter;
1158 Py_UCS4 *ucs4_out;
1159
Victor Stinner910337b2011-10-03 03:20:16 +02001160 assert(unicode != NULL);
1161 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001162 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1163 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1164
1165 for (iter = begin; iter < end; ) {
1166 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1167 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001168 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1169 && (iter+1) < end
1170 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001171 {
Victor Stinner551ac952011-11-29 22:58:13 +01001172 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 iter += 2;
1174 }
1175 else {
1176 *ucs4_out++ = *iter;
1177 iter++;
1178 }
1179 }
1180 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1181 _PyUnicode_GET_LENGTH(unicode)));
1182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001183}
1184#endif
1185
Victor Stinnercd9950f2011-10-02 00:34:53 +02001186static int
Victor Stinner488fa492011-12-12 00:01:39 +01001187unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001188{
Victor Stinner488fa492011-12-12 00:01:39 +01001189 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001190 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001191 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001192 return -1;
1193 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001194 return 0;
1195}
1196
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001197static int
1198_copy_characters(PyObject *to, Py_ssize_t to_start,
1199 PyObject *from, Py_ssize_t from_start,
1200 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001202 unsigned int from_kind, to_kind;
1203 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204
Victor Stinneree4544c2012-05-09 22:24:08 +02001205 assert(0 <= how_many);
1206 assert(0 <= from_start);
1207 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001208 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001209 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001210 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001211
Victor Stinnerd3f08822012-05-29 12:57:52 +02001212 assert(PyUnicode_Check(to));
1213 assert(PyUnicode_IS_READY(to));
1214 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1215
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001216 if (how_many == 0)
1217 return 0;
1218
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001222 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223
Victor Stinnerf1852262012-06-16 16:38:26 +02001224#ifdef Py_DEBUG
1225 if (!check_maxchar
1226 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1227 {
1228 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1229 Py_UCS4 ch;
1230 Py_ssize_t i;
1231 for (i=0; i < how_many; i++) {
1232 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1233 assert(ch <= to_maxchar);
1234 }
1235 }
1236#endif
1237
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001238 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001239 if (check_maxchar
1240 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1241 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001242 /* Writing Latin-1 characters into an ASCII string requires to
1243 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001244 Py_UCS4 max_char;
1245 max_char = ucs1lib_find_max_char(from_data,
1246 (Py_UCS1*)from_data + how_many);
1247 if (max_char >= 128)
1248 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001249 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001250 Py_MEMCPY((char*)to_data + to_kind * to_start,
1251 (char*)from_data + from_kind * from_start,
1252 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001253 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001254 else if (from_kind == PyUnicode_1BYTE_KIND
1255 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001256 {
1257 _PyUnicode_CONVERT_BYTES(
1258 Py_UCS1, Py_UCS2,
1259 PyUnicode_1BYTE_DATA(from) + from_start,
1260 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1261 PyUnicode_2BYTE_DATA(to) + to_start
1262 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001263 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001264 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001265 && to_kind == PyUnicode_4BYTE_KIND)
1266 {
1267 _PyUnicode_CONVERT_BYTES(
1268 Py_UCS1, Py_UCS4,
1269 PyUnicode_1BYTE_DATA(from) + from_start,
1270 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1271 PyUnicode_4BYTE_DATA(to) + to_start
1272 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001273 }
1274 else if (from_kind == PyUnicode_2BYTE_KIND
1275 && to_kind == PyUnicode_4BYTE_KIND)
1276 {
1277 _PyUnicode_CONVERT_BYTES(
1278 Py_UCS2, Py_UCS4,
1279 PyUnicode_2BYTE_DATA(from) + from_start,
1280 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1281 PyUnicode_4BYTE_DATA(to) + to_start
1282 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001283 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001284 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001285 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1286
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001287 if (!check_maxchar) {
1288 if (from_kind == PyUnicode_2BYTE_KIND
1289 && to_kind == PyUnicode_1BYTE_KIND)
1290 {
1291 _PyUnicode_CONVERT_BYTES(
1292 Py_UCS2, Py_UCS1,
1293 PyUnicode_2BYTE_DATA(from) + from_start,
1294 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1295 PyUnicode_1BYTE_DATA(to) + to_start
1296 );
1297 }
1298 else if (from_kind == PyUnicode_4BYTE_KIND
1299 && to_kind == PyUnicode_1BYTE_KIND)
1300 {
1301 _PyUnicode_CONVERT_BYTES(
1302 Py_UCS4, Py_UCS1,
1303 PyUnicode_4BYTE_DATA(from) + from_start,
1304 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1305 PyUnicode_1BYTE_DATA(to) + to_start
1306 );
1307 }
1308 else if (from_kind == PyUnicode_4BYTE_KIND
1309 && to_kind == PyUnicode_2BYTE_KIND)
1310 {
1311 _PyUnicode_CONVERT_BYTES(
1312 Py_UCS4, Py_UCS2,
1313 PyUnicode_4BYTE_DATA(from) + from_start,
1314 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1315 PyUnicode_2BYTE_DATA(to) + to_start
1316 );
1317 }
1318 else {
1319 assert(0);
1320 return -1;
1321 }
1322 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001323 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001325 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001326 Py_ssize_t i;
1327
Victor Stinnera0702ab2011-09-29 14:14:38 +02001328 for (i=0; i < how_many; i++) {
1329 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001330 if (ch > to_maxchar)
1331 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001332 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1333 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001334 }
1335 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001336 return 0;
1337}
1338
Victor Stinnerd3f08822012-05-29 12:57:52 +02001339void
1340_PyUnicode_FastCopyCharacters(
1341 PyObject *to, Py_ssize_t to_start,
1342 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001343{
1344 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1345}
1346
1347Py_ssize_t
1348PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1349 PyObject *from, Py_ssize_t from_start,
1350 Py_ssize_t how_many)
1351{
1352 int err;
1353
1354 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1355 PyErr_BadInternalCall();
1356 return -1;
1357 }
1358
Benjamin Petersonbac79492012-01-14 13:34:47 -05001359 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001360 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001361 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001362 return -1;
1363
Victor Stinnerd3f08822012-05-29 12:57:52 +02001364 if (from_start < 0) {
1365 PyErr_SetString(PyExc_IndexError, "string index out of range");
1366 return -1;
1367 }
1368 if (to_start < 0) {
1369 PyErr_SetString(PyExc_IndexError, "string index out of range");
1370 return -1;
1371 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001372 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1373 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1374 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001375 "Cannot write %zi characters at %zi "
1376 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001377 how_many, to_start, PyUnicode_GET_LENGTH(to));
1378 return -1;
1379 }
1380
1381 if (how_many == 0)
1382 return 0;
1383
Victor Stinner488fa492011-12-12 00:01:39 +01001384 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001385 return -1;
1386
1387 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1388 if (err) {
1389 PyErr_Format(PyExc_SystemError,
1390 "Cannot copy %s characters "
1391 "into a string of %s characters",
1392 unicode_kind_name(from),
1393 unicode_kind_name(to));
1394 return -1;
1395 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001396 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001397}
1398
Victor Stinner17222162011-09-28 22:15:37 +02001399/* Find the maximum code point and count the number of surrogate pairs so a
1400 correct string length can be computed before converting a string to UCS4.
1401 This function counts single surrogates as a character and not as a pair.
1402
1403 Return 0 on success, or -1 on error. */
1404static int
1405find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1406 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407{
1408 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001409 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410
Victor Stinnerc53be962011-10-02 21:33:54 +02001411 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 *num_surrogates = 0;
1413 *maxchar = 0;
1414
1415 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001417 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1418 && (iter+1) < end
1419 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1420 {
1421 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1422 ++(*num_surrogates);
1423 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 }
1425 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001427 {
1428 ch = *iter;
1429 iter++;
1430 }
1431 if (ch > *maxchar) {
1432 *maxchar = ch;
1433 if (*maxchar > MAX_UNICODE) {
1434 PyErr_Format(PyExc_ValueError,
1435 "character U+%x is not in range [U+0000; U+10ffff]",
1436 ch);
1437 return -1;
1438 }
1439 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 }
1441 return 0;
1442}
1443
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001444int
1445_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446{
1447 wchar_t *end;
1448 Py_UCS4 maxchar = 0;
1449 Py_ssize_t num_surrogates;
1450#if SIZEOF_WCHAR_T == 2
1451 Py_ssize_t length_wo_surrogates;
1452#endif
1453
Georg Brandl7597add2011-10-05 16:36:47 +02001454 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001455 strings were created using _PyObject_New() and where no canonical
1456 representation (the str field) has been set yet aka strings
1457 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001458 assert(_PyUnicode_CHECK(unicode));
1459 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001462 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001463 /* Actually, it should neither be interned nor be anything else: */
1464 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001467 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001468 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470
1471 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001472 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1473 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 PyErr_NoMemory();
1475 return -1;
1476 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001477 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 _PyUnicode_WSTR(unicode), end,
1479 PyUnicode_1BYTE_DATA(unicode));
1480 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1481 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1482 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1483 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001484 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001485 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001486 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001487 }
1488 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001489 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001490 _PyUnicode_UTF8(unicode) = NULL;
1491 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 }
1493 PyObject_FREE(_PyUnicode_WSTR(unicode));
1494 _PyUnicode_WSTR(unicode) = NULL;
1495 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1496 }
1497 /* In this case we might have to convert down from 4-byte native
1498 wchar_t to 2-byte unicode. */
1499 else if (maxchar < 65536) {
1500 assert(num_surrogates == 0 &&
1501 "FindMaxCharAndNumSurrogatePairs() messed up");
1502
Victor Stinner506f5922011-09-28 22:34:18 +02001503#if SIZEOF_WCHAR_T == 2
1504 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001505 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001506 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1507 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1508 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001509 _PyUnicode_UTF8(unicode) = NULL;
1510 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001511#else
1512 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001513 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001514 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001515 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001516 PyErr_NoMemory();
1517 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001518 }
Victor Stinner506f5922011-09-28 22:34:18 +02001519 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1520 _PyUnicode_WSTR(unicode), end,
1521 PyUnicode_2BYTE_DATA(unicode));
1522 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1523 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1524 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001525 _PyUnicode_UTF8(unicode) = NULL;
1526 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001527 PyObject_FREE(_PyUnicode_WSTR(unicode));
1528 _PyUnicode_WSTR(unicode) = NULL;
1529 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1530#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001531 }
1532 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1533 else {
1534#if SIZEOF_WCHAR_T == 2
1535 /* in case the native representation is 2-bytes, we need to allocate a
1536 new normalized 4-byte version. */
1537 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001538 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1539 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyErr_NoMemory();
1541 return -1;
1542 }
1543 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1544 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001545 _PyUnicode_UTF8(unicode) = NULL;
1546 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001547 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1548 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001549 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 PyObject_FREE(_PyUnicode_WSTR(unicode));
1551 _PyUnicode_WSTR(unicode) = NULL;
1552 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1553#else
1554 assert(num_surrogates == 0);
1555
Victor Stinnerc3c74152011-10-02 20:39:55 +02001556 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1561#endif
1562 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1563 }
1564 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return 0;
1567}
1568
Alexander Belopolsky40018472011-02-26 01:02:56 +00001569static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001570unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571{
Walter Dörwald16807132007-05-25 13:52:07 +00001572 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_NOT_INTERNED:
1574 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001575
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_INTERNED_MORTAL:
1577 /* revive dead object temporarily for DelItem */
1578 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001579 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 Py_FatalError(
1581 "deletion of interned string failed");
1582 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 case SSTATE_INTERNED_IMMORTAL:
1585 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 default:
1588 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589 }
1590
Victor Stinner03490912011-10-03 23:45:12 +02001591 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001593 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001594 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1596 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001599}
1600
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601#ifdef Py_DEBUG
1602static int
1603unicode_is_singleton(PyObject *unicode)
1604{
1605 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1606 if (unicode == unicode_empty)
1607 return 1;
1608 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1609 {
1610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1611 if (ch < 256 && unicode_latin1[ch] == unicode)
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif
1617
Alexander Belopolsky40018472011-02-26 01:02:56 +00001618static int
Victor Stinner488fa492011-12-12 00:01:39 +01001619unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620{
Victor Stinner488fa492011-12-12 00:01:39 +01001621 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001622 if (Py_REFCNT(unicode) != 1)
1623 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001624 if (_PyUnicode_HASH(unicode) != -1)
1625 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (PyUnicode_CHECK_INTERNED(unicode))
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (!PyUnicode_CheckExact(unicode))
1629 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001631 /* singleton refcount is greater than 1 */
1632 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 return 1;
1635}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637static int
1638unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1639{
1640 PyObject *unicode;
1641 Py_ssize_t old_length;
1642
1643 assert(p_unicode != NULL);
1644 unicode = *p_unicode;
1645
1646 assert(unicode != NULL);
1647 assert(PyUnicode_Check(unicode));
1648 assert(0 <= length);
1649
Victor Stinner910337b2011-10-03 03:20:16 +02001650 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001651 old_length = PyUnicode_WSTR_LENGTH(unicode);
1652 else
1653 old_length = PyUnicode_GET_LENGTH(unicode);
1654 if (old_length == length)
1655 return 0;
1656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001657 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001658 _Py_INCREF_UNICODE_EMPTY();
1659 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001660 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001663 return 0;
1664 }
1665
Victor Stinner488fa492011-12-12 00:01:39 +01001666 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 PyObject *copy = resize_copy(unicode, length);
1668 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 Py_DECREF(*p_unicode);
1671 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673 }
1674
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 PyObject *new_unicode = resize_compact(unicode, length);
1677 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001680 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001681 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001683}
1684
Alexander Belopolsky40018472011-02-26 01:02:56 +00001685int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001687{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 PyObject *unicode;
1689 if (p_unicode == NULL) {
1690 PyErr_BadInternalCall();
1691 return -1;
1692 }
1693 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 {
1696 PyErr_BadInternalCall();
1697 return -1;
1698 }
1699 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001700}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001701
Victor Stinnerc5166102012-02-22 13:55:02 +01001702/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001703
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001704 WARNING: The function doesn't copy the terminating null character and
1705 doesn't check the maximum character (may write a latin1 character in an
1706 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001707static void
1708unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1709 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001710{
1711 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1712 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001713 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
1715 switch (kind) {
1716 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001718#ifdef Py_DEBUG
1719 if (PyUnicode_IS_ASCII(unicode)) {
1720 Py_UCS4 maxchar = ucs1lib_find_max_char(
1721 (const Py_UCS1*)str,
1722 (const Py_UCS1*)str + len);
1723 assert(maxchar < 128);
1724 }
1725#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001726 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001727 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 }
1729 case PyUnicode_2BYTE_KIND: {
1730 Py_UCS2 *start = (Py_UCS2 *)data + index;
1731 Py_UCS2 *ucs2 = start;
1732 assert(index <= PyUnicode_GET_LENGTH(unicode));
1733
Victor Stinner184252a2012-06-16 02:57:41 +02001734 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 *ucs2 = (Py_UCS2)*str;
1736
1737 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 default: {
1741 Py_UCS4 *start = (Py_UCS4 *)data + index;
1742 Py_UCS4 *ucs4 = start;
1743 assert(kind == PyUnicode_4BYTE_KIND);
1744 assert(index <= PyUnicode_GET_LENGTH(unicode));
1745
Victor Stinner184252a2012-06-16 02:57:41 +02001746 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 *ucs4 = (Py_UCS4)*str;
1748
1749 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 }
1752}
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754static PyObject*
1755get_latin1_char(unsigned char ch)
1756{
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001759 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 if (!unicode)
1761 return NULL;
1762 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001763 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 unicode_latin1[ch] = unicode;
1765 }
1766 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001767 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768}
1769
Victor Stinner985a82a2014-01-03 12:53:47 +01001770static PyObject*
1771unicode_char(Py_UCS4 ch)
1772{
1773 PyObject *unicode;
1774
1775 assert(ch <= MAX_UNICODE);
1776
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001777 if (ch < 256)
1778 return get_latin1_char(ch);
1779
Victor Stinner985a82a2014-01-03 12:53:47 +01001780 unicode = PyUnicode_New(1, ch);
1781 if (unicode == NULL)
1782 return NULL;
1783 switch (PyUnicode_KIND(unicode)) {
1784 case PyUnicode_1BYTE_KIND:
1785 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1789 break;
1790 default:
1791 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1792 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1793 }
1794 assert(_PyUnicode_CheckConsistency(unicode, 1));
1795 return unicode;
1796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001801 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 Py_UCS4 maxchar = 0;
1803 Py_ssize_t num_surrogates;
1804
1805 if (u == NULL)
1806 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808 /* If the Unicode data is known at construction time, we can apply
1809 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001812 if (size == 0)
1813 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Single character Unicode objects in the Latin-1 range are
1816 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001817 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return get_latin1_char((unsigned char)*u);
1819
1820 /* If not empty and not single character, copy the Unicode data
1821 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001822 if (find_maxchar_surrogates(u, u + size,
1823 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return NULL;
1825
Victor Stinner8faf8212011-12-08 22:14:11 +01001826 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001827 if (!unicode)
1828 return NULL;
1829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 switch (PyUnicode_KIND(unicode)) {
1831 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001832 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1834 break;
1835 case PyUnicode_2BYTE_KIND:
1836#if Py_UNICODE_SIZE == 2
1837 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1838#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1841#endif
1842 break;
1843 case PyUnicode_4BYTE_KIND:
1844#if SIZEOF_WCHAR_T == 2
1845 /* This is the only case which has to process surrogates, thus
1846 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001847 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848#else
1849 assert(num_surrogates == 0);
1850 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1851#endif
1852 break;
1853 default:
1854 assert(0 && "Impossible state");
1855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001857 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858}
1859
Alexander Belopolsky40018472011-02-26 01:02:56 +00001860PyObject *
1861PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001862{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 if (size < 0) {
1864 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 return NULL;
1867 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001868 if (u != NULL)
1869 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1870 else
1871 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874PyObject *
1875PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876{
1877 size_t size = strlen(u);
1878 if (size > PY_SSIZE_T_MAX) {
1879 PyErr_SetString(PyExc_OverflowError, "input too long");
1880 return NULL;
1881 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001882 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883}
1884
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001885PyObject *
1886_PyUnicode_FromId(_Py_Identifier *id)
1887{
1888 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001889 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1890 strlen(id->string),
1891 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892 if (!id->object)
1893 return NULL;
1894 PyUnicode_InternInPlace(&id->object);
1895 assert(!id->next);
1896 id->next = static_strings;
1897 static_strings = id;
1898 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 return id->object;
1900}
1901
1902void
1903_PyUnicode_ClearStaticStrings()
1904{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001905 _Py_Identifier *tmp, *s = static_strings;
1906 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001907 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 tmp = s->next;
1909 s->next = NULL;
1910 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001911 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001913}
1914
Benjamin Peterson0df54292012-03-26 14:50:32 -04001915/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917PyObject*
1918_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001919{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001921 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001922 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001923#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001924 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001925#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001927 }
Victor Stinner785938e2011-12-11 20:09:03 +01001928 unicode = PyUnicode_New(size, 127);
1929 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001930 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001931 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1932 assert(_PyUnicode_CheckConsistency(unicode, 1));
1933 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001934}
1935
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001936static Py_UCS4
1937kind_maxchar_limit(unsigned int kind)
1938{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001939 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940 case PyUnicode_1BYTE_KIND:
1941 return 0x80;
1942 case PyUnicode_2BYTE_KIND:
1943 return 0x100;
1944 case PyUnicode_4BYTE_KIND:
1945 return 0x10000;
1946 default:
1947 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001948 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 }
1950}
1951
Victor Stinnere6abb482012-05-02 01:15:40 +02001952Py_LOCAL_INLINE(Py_UCS4)
1953align_maxchar(Py_UCS4 maxchar)
1954{
1955 if (maxchar <= 127)
1956 return 127;
1957 else if (maxchar <= 255)
1958 return 255;
1959 else if (maxchar <= 65535)
1960 return 65535;
1961 else
1962 return MAX_UNICODE;
1963}
1964
Victor Stinner702c7342011-10-05 13:50:52 +02001965static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001966_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001974 if (size == 1)
1975 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001978 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 if (!res)
1980 return NULL;
1981 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001982 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001984}
1985
Victor Stinnere57b1c02011-09-28 22:20:48 +02001986static PyObject*
1987_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988{
1989 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001991
Serhiy Storchaka678db842013-01-26 12:16:36 +02001992 if (size == 0)
1993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001995 if (size == 1)
1996 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001998 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001999 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 if (!res)
2001 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002004 else {
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2007 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002008 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 return res;
2010}
2011
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012static PyObject*
2013_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014{
2015 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002016 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017
Serhiy Storchaka678db842013-01-26 12:16:36 +02002018 if (size == 0)
2019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 if (size == 1)
2022 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002024 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 if (!res)
2027 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002028 if (max_char < 256)
2029 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2030 PyUnicode_1BYTE_DATA(res));
2031 else if (max_char < 0x10000)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2033 PyUnicode_2BYTE_DATA(res));
2034 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002036 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 return res;
2038}
2039
2040PyObject*
2041PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2042{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002043 if (size < 0) {
2044 PyErr_SetString(PyExc_ValueError, "size must be positive");
2045 return NULL;
2046 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002047 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002049 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002051 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002055 PyErr_SetString(PyExc_SystemError, "invalid kind");
2056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058}
2059
Victor Stinnerece58de2012-04-23 23:36:38 +02002060Py_UCS4
2061_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2062{
2063 enum PyUnicode_Kind kind;
2064 void *startptr, *endptr;
2065
2066 assert(PyUnicode_IS_READY(unicode));
2067 assert(0 <= start);
2068 assert(end <= PyUnicode_GET_LENGTH(unicode));
2069 assert(start <= end);
2070
2071 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2072 return PyUnicode_MAX_CHAR_VALUE(unicode);
2073
2074 if (start == end)
2075 return 127;
2076
Victor Stinner94d558b2012-04-27 22:26:58 +02002077 if (PyUnicode_IS_ASCII(unicode))
2078 return 127;
2079
Victor Stinnerece58de2012-04-23 23:36:38 +02002080 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002081 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002082 endptr = (char *)startptr + end * kind;
2083 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 switch(kind) {
2085 case PyUnicode_1BYTE_KIND:
2086 return ucs1lib_find_max_char(startptr, endptr);
2087 case PyUnicode_2BYTE_KIND:
2088 return ucs2lib_find_max_char(startptr, endptr);
2089 case PyUnicode_4BYTE_KIND:
2090 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002092 assert(0);
2093 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 }
2095}
2096
Victor Stinner25a4b292011-10-06 12:31:55 +02002097/* Ensure that a string uses the most efficient storage, if it is not the
2098 case: create a new string with of the right kind. Write NULL into *p_unicode
2099 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002100static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002101unicode_adjust_maxchar(PyObject **p_unicode)
2102{
2103 PyObject *unicode, *copy;
2104 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 unsigned int kind;
2107
2108 assert(p_unicode != NULL);
2109 unicode = *p_unicode;
2110 assert(PyUnicode_IS_READY(unicode));
2111 if (PyUnicode_IS_ASCII(unicode))
2112 return;
2113
2114 len = PyUnicode_GET_LENGTH(unicode);
2115 kind = PyUnicode_KIND(unicode);
2116 if (kind == PyUnicode_1BYTE_KIND) {
2117 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002118 max_char = ucs1lib_find_max_char(u, u + len);
2119 if (max_char >= 128)
2120 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002121 }
2122 else if (kind == PyUnicode_2BYTE_KIND) {
2123 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 max_char = ucs2lib_find_max_char(u, u + len);
2125 if (max_char >= 256)
2126 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 }
2128 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs4lib_find_max_char(u, u + len);
2132 if (max_char >= 0x10000)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002135 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002136 if (copy != NULL)
2137 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 Py_DECREF(unicode);
2139 *p_unicode = copy;
2140}
2141
Victor Stinner034f6cf2011-09-30 02:26:44 +02002142PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002143_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002144{
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002147
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_BadInternalCall();
2150 return NULL;
2151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002152 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner87af4f22011-11-21 23:03:47 +01002155 length = PyUnicode_GET_LENGTH(unicode);
2156 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 if (!copy)
2158 return NULL;
2159 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2160
Victor Stinner87af4f22011-11-21 23:03:47 +01002161 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2162 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002163 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002165}
2166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002167
Victor Stinnerbc603d12011-10-02 01:00:40 +02002168/* Widen Unicode objects to larger buffers. Don't write terminating null
2169 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
2171void*
2172_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2173{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 Py_ssize_t len;
2175 void *result;
2176 unsigned int skind;
2177
Benjamin Petersonbac79492012-01-14 13:34:47 -05002178 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179 return NULL;
2180
2181 len = PyUnicode_GET_LENGTH(s);
2182 skind = PyUnicode_KIND(s);
2183 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002184 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 return NULL;
2186 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 case PyUnicode_2BYTE_KIND:
2189 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2190 if (!result)
2191 return PyErr_NoMemory();
2192 assert(skind == PyUnicode_1BYTE_KIND);
2193 _PyUnicode_CONVERT_BYTES(
2194 Py_UCS1, Py_UCS2,
2195 PyUnicode_1BYTE_DATA(s),
2196 PyUnicode_1BYTE_DATA(s) + len,
2197 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_4BYTE_KIND:
2200 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2201 if (!result)
2202 return PyErr_NoMemory();
2203 if (skind == PyUnicode_2BYTE_KIND) {
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS2, Py_UCS4,
2206 PyUnicode_2BYTE_DATA(s),
2207 PyUnicode_2BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 else {
2211 assert(skind == PyUnicode_1BYTE_KIND);
2212 _PyUnicode_CONVERT_BYTES(
2213 Py_UCS1, Py_UCS4,
2214 PyUnicode_1BYTE_DATA(s),
2215 PyUnicode_1BYTE_DATA(s) + len,
2216 result);
2217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 default:
2220 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 }
Victor Stinner01698042011-10-04 00:04:26 +02002222 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 return NULL;
2224}
2225
2226static Py_UCS4*
2227as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
2230 int kind;
2231 void *data;
2232 Py_ssize_t len, targetlen;
2233 if (PyUnicode_READY(string) == -1)
2234 return NULL;
2235 kind = PyUnicode_KIND(string);
2236 data = PyUnicode_DATA(string);
2237 len = PyUnicode_GET_LENGTH(string);
2238 targetlen = len;
2239 if (copy_null)
2240 targetlen++;
2241 if (!target) {
2242 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2247 if (!target) {
2248 PyErr_NoMemory();
2249 return NULL;
2250 }
2251 }
2252 else {
2253 if (targetsize < targetlen) {
2254 PyErr_Format(PyExc_SystemError,
2255 "string is longer than the buffer");
2256 if (copy_null && 0 < targetsize)
2257 target[0] = 0;
2258 return NULL;
2259 }
2260 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002261 if (kind == PyUnicode_1BYTE_KIND) {
2262 Py_UCS1 *start = (Py_UCS1 *) data;
2263 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002265 else if (kind == PyUnicode_2BYTE_KIND) {
2266 Py_UCS2 *start = (Py_UCS2 *) data;
2267 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2268 }
2269 else {
2270 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 if (copy_null)
2274 target[len] = 0;
2275 return target;
2276}
2277
2278Py_UCS4*
2279PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2280 int copy_null)
2281{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002282 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002283 PyErr_BadInternalCall();
2284 return NULL;
2285 }
2286 return as_ucs4(string, target, targetsize, copy_null);
2287}
2288
2289Py_UCS4*
2290PyUnicode_AsUCS4Copy(PyObject *string)
2291{
2292 return as_ucs4(string, NULL, 0, 1);
2293}
2294
2295#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002296
Alexander Belopolsky40018472011-02-26 01:02:56 +00002297PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002298PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002301 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002302 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002303 PyErr_BadInternalCall();
2304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002305 }
2306
Martin v. Löwis790465f2008-04-05 20:41:37 +00002307 if (size == -1) {
2308 size = wcslen(w);
2309 }
2310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002311 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002312}
2313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002314#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002315
Walter Dörwald346737f2007-05-31 10:44:43 +00002316static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002317makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
Victor Stinnere215d962012-10-06 23:03:36 +02002318 char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002319{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002320 *fmt++ = '%';
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 if (longflag)
2322 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002323 else if (longlongflag) {
2324 /* longlongflag should only ever be nonzero on machines with
2325 HAVE_LONG_LONG defined */
2326#ifdef HAVE_LONG_LONG
2327 char *f = PY_FORMAT_LONG_LONG;
2328 while (*f)
2329 *fmt++ = *f++;
2330#else
2331 /* we shouldn't ever get here */
2332 assert(0);
2333 *fmt++ = 'l';
2334#endif
2335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002336 else if (size_tflag) {
2337 char *f = PY_FORMAT_SIZE_T;
2338 while (*f)
2339 *fmt++ = *f++;
2340 }
2341 *fmt++ = c;
2342 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002343}
2344
Victor Stinner15a11362012-10-06 23:48:20 +02002345/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002346 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2347 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2348#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002349
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002350static int
2351unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2352 Py_ssize_t width, Py_ssize_t precision)
2353{
2354 Py_ssize_t length, fill, arglen;
2355 Py_UCS4 maxchar;
2356
2357 if (PyUnicode_READY(str) == -1)
2358 return -1;
2359
2360 length = PyUnicode_GET_LENGTH(str);
2361 if ((precision == -1 || precision >= length)
2362 && width <= length)
2363 return _PyUnicodeWriter_WriteStr(writer, str);
2364
2365 if (precision != -1)
2366 length = Py_MIN(precision, length);
2367
2368 arglen = Py_MAX(length, width);
2369 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2370 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2371 else
2372 maxchar = writer->maxchar;
2373
2374 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2375 return -1;
2376
2377 if (width > length) {
2378 fill = width - length;
2379 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2380 return -1;
2381 writer->pos += fill;
2382 }
2383
2384 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2385 str, 0, length);
2386 writer->pos += length;
2387 return 0;
2388}
2389
2390static int
2391unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2392 Py_ssize_t width, Py_ssize_t precision)
2393{
2394 /* UTF-8 */
2395 Py_ssize_t length;
2396 PyObject *unicode;
2397 int res;
2398
2399 length = strlen(str);
2400 if (precision != -1)
2401 length = Py_MIN(length, precision);
2402 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2403 if (unicode == NULL)
2404 return -1;
2405
2406 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2407 Py_DECREF(unicode);
2408 return res;
2409}
2410
Victor Stinner96865452011-03-01 23:44:09 +00002411static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002412unicode_fromformat_arg(_PyUnicodeWriter *writer,
2413 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002414{
Victor Stinnere215d962012-10-06 23:03:36 +02002415 const char *p;
2416 Py_ssize_t len;
2417 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002418 Py_ssize_t width;
2419 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002420 int longflag;
2421 int longlongflag;
2422 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002423 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002424
2425 p = f;
2426 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002427 zeropad = 0;
2428 if (*f == '0') {
2429 zeropad = 1;
2430 f++;
2431 }
Victor Stinner96865452011-03-01 23:44:09 +00002432
2433 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002434 width = -1;
2435 if (Py_ISDIGIT((unsigned)*f)) {
2436 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002437 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002438 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002439 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002440 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002441 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002442 return NULL;
2443 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002444 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002445 f++;
2446 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002447 }
2448 precision = -1;
2449 if (*f == '.') {
2450 f++;
2451 if (Py_ISDIGIT((unsigned)*f)) {
2452 precision = (*f - '0');
2453 f++;
2454 while (Py_ISDIGIT((unsigned)*f)) {
2455 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2456 PyErr_SetString(PyExc_ValueError,
2457 "precision too big");
2458 return NULL;
2459 }
2460 precision = (precision * 10) + (*f - '0');
2461 f++;
2462 }
2463 }
Victor Stinner96865452011-03-01 23:44:09 +00002464 if (*f == '%') {
2465 /* "%.3%s" => f points to "3" */
2466 f--;
2467 }
2468 }
2469 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002470 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002471 f--;
2472 }
Victor Stinner96865452011-03-01 23:44:09 +00002473
2474 /* Handle %ld, %lu, %lld and %llu. */
2475 longflag = 0;
2476 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002477 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002478 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002479 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002480 longflag = 1;
2481 ++f;
2482 }
2483#ifdef HAVE_LONG_LONG
2484 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002485 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002486 longlongflag = 1;
2487 f += 2;
2488 }
2489#endif
2490 }
2491 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002492 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002493 size_tflag = 1;
2494 ++f;
2495 }
Victor Stinnere215d962012-10-06 23:03:36 +02002496
2497 if (f[1] == '\0')
2498 writer->overallocate = 0;
2499
2500 switch (*f) {
2501 case 'c':
2502 {
2503 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002504 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002505 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002506 "character argument not in range(0x110000)");
2507 return NULL;
2508 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002509 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002510 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002511 break;
2512 }
2513
2514 case 'i':
2515 case 'd':
2516 case 'u':
2517 case 'x':
2518 {
2519 /* used by sprintf */
2520 char fmt[10]; /* should be enough for "%0lld\0" */
Victor Stinner15a11362012-10-06 23:48:20 +02002521 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002522 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002523
2524 if (*f == 'u') {
2525 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2526
2527 if (longflag)
2528 len = sprintf(buffer, fmt,
2529 va_arg(*vargs, unsigned long));
2530#ifdef HAVE_LONG_LONG
2531 else if (longlongflag)
2532 len = sprintf(buffer, fmt,
2533 va_arg(*vargs, unsigned PY_LONG_LONG));
2534#endif
2535 else if (size_tflag)
2536 len = sprintf(buffer, fmt,
2537 va_arg(*vargs, size_t));
2538 else
2539 len = sprintf(buffer, fmt,
2540 va_arg(*vargs, unsigned int));
2541 }
2542 else if (*f == 'x') {
2543 makefmt(fmt, 0, 0, 0, 'x');
2544 len = sprintf(buffer, fmt, va_arg(*vargs, int));
2545 }
2546 else {
2547 makefmt(fmt, longflag, longlongflag, size_tflag, *f);
2548
2549 if (longflag)
2550 len = sprintf(buffer, fmt,
2551 va_arg(*vargs, long));
2552#ifdef HAVE_LONG_LONG
2553 else if (longlongflag)
2554 len = sprintf(buffer, fmt,
2555 va_arg(*vargs, PY_LONG_LONG));
2556#endif
2557 else if (size_tflag)
2558 len = sprintf(buffer, fmt,
2559 va_arg(*vargs, Py_ssize_t));
2560 else
2561 len = sprintf(buffer, fmt,
2562 va_arg(*vargs, int));
2563 }
2564 assert(len >= 0);
2565
Victor Stinnere215d962012-10-06 23:03:36 +02002566 if (precision < len)
2567 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002568
2569 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002570 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2571 return NULL;
2572
Victor Stinnere215d962012-10-06 23:03:36 +02002573 if (width > precision) {
2574 Py_UCS4 fillchar;
2575 fill = width - precision;
2576 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002577 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2578 return NULL;
2579 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002580 }
Victor Stinner15a11362012-10-06 23:48:20 +02002581 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002582 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002583 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2584 return NULL;
2585 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002586 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002587
Victor Stinner4a587072013-11-19 12:54:53 +01002588 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2589 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002590 break;
2591 }
2592
2593 case 'p':
2594 {
2595 char number[MAX_LONG_LONG_CHARS];
2596
2597 len = sprintf(number, "%p", va_arg(*vargs, void*));
2598 assert(len >= 0);
2599
2600 /* %p is ill-defined: ensure leading 0x. */
2601 if (number[1] == 'X')
2602 number[1] = 'x';
2603 else if (number[1] != 'x') {
2604 memmove(number + 2, number,
2605 strlen(number) + 1);
2606 number[0] = '0';
2607 number[1] = 'x';
2608 len += 2;
2609 }
2610
Victor Stinner4a587072013-11-19 12:54:53 +01002611 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002612 return NULL;
2613 break;
2614 }
2615
2616 case 's':
2617 {
2618 /* UTF-8 */
2619 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002620 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002621 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002622 break;
2623 }
2624
2625 case 'U':
2626 {
2627 PyObject *obj = va_arg(*vargs, PyObject *);
2628 assert(obj && _PyUnicode_CHECK(obj));
2629
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002630 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002631 return NULL;
2632 break;
2633 }
2634
2635 case 'V':
2636 {
2637 PyObject *obj = va_arg(*vargs, PyObject *);
2638 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002639 if (obj) {
2640 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
2643 }
2644 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002645 assert(str != NULL);
2646 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002647 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002648 }
2649 break;
2650 }
2651
2652 case 'S':
2653 {
2654 PyObject *obj = va_arg(*vargs, PyObject *);
2655 PyObject *str;
2656 assert(obj);
2657 str = PyObject_Str(obj);
2658 if (!str)
2659 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002660 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002661 Py_DECREF(str);
2662 return NULL;
2663 }
2664 Py_DECREF(str);
2665 break;
2666 }
2667
2668 case 'R':
2669 {
2670 PyObject *obj = va_arg(*vargs, PyObject *);
2671 PyObject *repr;
2672 assert(obj);
2673 repr = PyObject_Repr(obj);
2674 if (!repr)
2675 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002676 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002677 Py_DECREF(repr);
2678 return NULL;
2679 }
2680 Py_DECREF(repr);
2681 break;
2682 }
2683
2684 case 'A':
2685 {
2686 PyObject *obj = va_arg(*vargs, PyObject *);
2687 PyObject *ascii;
2688 assert(obj);
2689 ascii = PyObject_ASCII(obj);
2690 if (!ascii)
2691 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002692 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002693 Py_DECREF(ascii);
2694 return NULL;
2695 }
2696 Py_DECREF(ascii);
2697 break;
2698 }
2699
2700 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002701 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002702 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002703 break;
2704
2705 default:
2706 /* if we stumble upon an unknown formatting code, copy the rest
2707 of the format string to the output string. (we cannot just
2708 skip the code, since there's no way to know what's in the
2709 argument list) */
2710 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002711 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002712 return NULL;
2713 f = p+len;
2714 return f;
2715 }
2716
2717 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002718 return f;
2719}
2720
Walter Dörwaldd2034312007-05-18 16:29:38 +00002721PyObject *
2722PyUnicode_FromFormatV(const char *format, va_list vargs)
2723{
Victor Stinnere215d962012-10-06 23:03:36 +02002724 va_list vargs2;
2725 const char *f;
2726 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002727
Victor Stinner8f674cc2013-04-17 23:02:17 +02002728 _PyUnicodeWriter_Init(&writer);
2729 writer.min_length = strlen(format) + 100;
2730 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002731
2732 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2733 Copy it to be able to pass a reference to a subfunction. */
2734 Py_VA_COPY(vargs2, vargs);
2735
2736 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002737 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002738 f = unicode_fromformat_arg(&writer, f, &vargs2);
2739 if (f == NULL)
2740 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002742 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002743 const char *p;
2744 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002745
Victor Stinnere215d962012-10-06 23:03:36 +02002746 p = f;
2747 do
2748 {
2749 if ((unsigned char)*p > 127) {
2750 PyErr_Format(PyExc_ValueError,
2751 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2752 "string, got a non-ASCII byte: 0x%02x",
2753 (unsigned char)*p);
2754 return NULL;
2755 }
2756 p++;
2757 }
2758 while (*p != '\0' && *p != '%');
2759 len = p - f;
2760
2761 if (*p == '\0')
2762 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002763
2764 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002765 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002766
2767 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 }
Victor Stinnere215d962012-10-06 23:03:36 +02002770 return _PyUnicodeWriter_Finish(&writer);
2771
2772 fail:
2773 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002774 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002775}
2776
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777PyObject *
2778PyUnicode_FromFormat(const char *format, ...)
2779{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002780 PyObject* ret;
2781 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782
2783#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002784 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002785#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002786 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002787#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002788 ret = PyUnicode_FromFormatV(format, vargs);
2789 va_end(vargs);
2790 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002791}
2792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002793#ifdef HAVE_WCHAR_H
2794
Victor Stinner5593d8a2010-10-02 11:11:27 +00002795/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2796 convert a Unicode object to a wide character string.
2797
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 character) required to convert the unicode object. Ignore size argument.
2800
Victor Stinnerd88d9832011-09-06 02:00:05 +02002801 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002802 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002803 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002805unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002806 wchar_t *w,
2807 Py_ssize_t size)
2808{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002809 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002810 const wchar_t *wstr;
2811
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002812 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 if (wstr == NULL)
2814 return -1;
2815
Victor Stinner5593d8a2010-10-02 11:11:27 +00002816 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002817 if (size > res)
2818 size = res + 1;
2819 else
2820 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002822 return res;
2823 }
2824 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002825 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002826}
2827
2828Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002829PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002830 wchar_t *w,
2831 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832{
2833 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002834 PyErr_BadInternalCall();
2835 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002836 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002837 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002838}
2839
Victor Stinner137c34c2010-09-29 10:25:54 +00002840wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002841PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002842 Py_ssize_t *size)
2843{
2844 wchar_t* buffer;
2845 Py_ssize_t buflen;
2846
2847 if (unicode == NULL) {
2848 PyErr_BadInternalCall();
2849 return NULL;
2850 }
2851
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002852 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002853 if (buflen == -1)
2854 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002855 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002856 PyErr_NoMemory();
2857 return NULL;
2858 }
2859
Victor Stinner137c34c2010-09-29 10:25:54 +00002860 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2861 if (buffer == NULL) {
2862 PyErr_NoMemory();
2863 return NULL;
2864 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002865 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002866 if (buflen == -1) {
2867 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002869 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002870 if (size != NULL)
2871 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002872 return buffer;
2873}
2874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002875#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002879{
Victor Stinner8faf8212011-12-08 22:14:11 +01002880 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyErr_SetString(PyExc_ValueError,
2882 "chr() arg not in range(0x110000)");
2883 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002884 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002885
Victor Stinner985a82a2014-01-03 12:53:47 +01002886 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002887}
2888
Alexander Belopolsky40018472011-02-26 01:02:56 +00002889PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002890PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002893 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002895 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002896 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002897 Py_INCREF(obj);
2898 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 }
2900 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002901 /* For a Unicode subtype that's not a Unicode object,
2902 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002903 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002904 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002905 PyErr_Format(PyExc_TypeError,
2906 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002907 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002908 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002909}
2910
Alexander Belopolsky40018472011-02-26 01:02:56 +00002911PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002912PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002913 const char *encoding,
2914 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002915{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002916 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002917 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002918
Guido van Rossumd57fd912000-03-10 22:53:23 +00002919 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002920 PyErr_BadInternalCall();
2921 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002923
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002924 /* Decoding bytes objects is the most common case and should be fast */
2925 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002926 if (PyBytes_GET_SIZE(obj) == 0)
2927 _Py_RETURN_UNICODE_EMPTY();
2928 v = PyUnicode_Decode(
2929 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2930 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002931 return v;
2932 }
2933
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002934 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002935 PyErr_SetString(PyExc_TypeError,
2936 "decoding str is not supported");
2937 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002939
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002940 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2941 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2942 PyErr_Format(PyExc_TypeError,
2943 "coercing to str: need bytes, bytearray "
2944 "or buffer-like object, %.80s found",
2945 Py_TYPE(obj)->tp_name);
2946 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002947 }
Tim Petersced69f82003-09-16 20:30:58 +00002948
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002949 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002950 PyBuffer_Release(&buffer);
2951 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002952 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002953
Serhiy Storchaka05997252013-01-26 12:14:02 +02002954 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002955 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002956 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002957}
2958
Victor Stinner600d3be2010-06-10 12:00:55 +00002959/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002960 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2961 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002962int
2963_Py_normalize_encoding(const char *encoding,
2964 char *lower,
2965 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002966{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002967 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002968 char *l;
2969 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002970
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002971 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002972 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002973 if (lower_len < 6)
2974 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002975 strcpy(lower, "utf-8");
2976 return 1;
2977 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002978 e = encoding;
2979 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002980 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002981 while (*e) {
2982 if (l == l_end)
2983 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002984 if (Py_ISUPPER(*e)) {
2985 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002986 }
2987 else if (*e == '_') {
2988 *l++ = '-';
2989 e++;
2990 }
2991 else {
2992 *l++ = *e++;
2993 }
2994 }
2995 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002996 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002997}
2998
Alexander Belopolsky40018472011-02-26 01:02:56 +00002999PyObject *
3000PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003001 Py_ssize_t size,
3002 const char *encoding,
3003 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003004{
3005 PyObject *buffer = NULL, *unicode;
3006 Py_buffer info;
3007 char lower[11]; /* Enough for any encoding shortcut */
3008
Fred Drakee4315f52000-05-09 19:53:39 +00003009 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003010 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003011 if ((strcmp(lower, "utf-8") == 0) ||
3012 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003013 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003014 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003015 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003016 (strcmp(lower, "iso-8859-1") == 0) ||
3017 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003018 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003019#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003020 else if (strcmp(lower, "mbcs") == 0)
3021 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003022#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003023 else if (strcmp(lower, "ascii") == 0)
3024 return PyUnicode_DecodeASCII(s, size, errors);
3025 else if (strcmp(lower, "utf-16") == 0)
3026 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3027 else if (strcmp(lower, "utf-32") == 0)
3028 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3029 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030
3031 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003032 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003033 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003034 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003035 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036 if (buffer == NULL)
3037 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003038 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003039 if (unicode == NULL)
3040 goto onError;
3041 if (!PyUnicode_Check(unicode)) {
3042 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003043 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3044 "use codecs.decode() to decode to arbitrary types",
3045 encoding,
3046 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003047 Py_DECREF(unicode);
3048 goto onError;
3049 }
3050 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003051 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003052
Benjamin Peterson29060642009-01-31 22:14:21 +00003053 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003054 Py_XDECREF(buffer);
3055 return NULL;
3056}
3057
Alexander Belopolsky40018472011-02-26 01:02:56 +00003058PyObject *
3059PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003060 const char *encoding,
3061 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003062{
3063 PyObject *v;
3064
3065 if (!PyUnicode_Check(unicode)) {
3066 PyErr_BadArgument();
3067 goto onError;
3068 }
3069
3070 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072
3073 /* Decode via the codec registry */
3074 v = PyCodec_Decode(unicode, encoding, errors);
3075 if (v == NULL)
3076 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003077 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003078
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003080 return NULL;
3081}
3082
Alexander Belopolsky40018472011-02-26 01:02:56 +00003083PyObject *
3084PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003085 const char *encoding,
3086 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003087{
3088 PyObject *v;
3089
3090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
3092 goto onError;
3093 }
3094
3095 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003096 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097
3098 /* Decode via the codec registry */
3099 v = PyCodec_Decode(unicode, encoding, errors);
3100 if (v == NULL)
3101 goto onError;
3102 if (!PyUnicode_Check(v)) {
3103 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003104 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3105 "use codecs.decode() to decode to arbitrary types",
3106 encoding,
3107 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003108 Py_DECREF(v);
3109 goto onError;
3110 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003111 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003112
Benjamin Peterson29060642009-01-31 22:14:21 +00003113 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003114 return NULL;
3115}
3116
Alexander Belopolsky40018472011-02-26 01:02:56 +00003117PyObject *
3118PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003119 Py_ssize_t size,
3120 const char *encoding,
3121 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003122{
3123 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003124
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125 unicode = PyUnicode_FromUnicode(s, size);
3126 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003128 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3129 Py_DECREF(unicode);
3130 return v;
3131}
3132
Alexander Belopolsky40018472011-02-26 01:02:56 +00003133PyObject *
3134PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003135 const char *encoding,
3136 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003137{
3138 PyObject *v;
3139
3140 if (!PyUnicode_Check(unicode)) {
3141 PyErr_BadArgument();
3142 goto onError;
3143 }
3144
3145 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003147
3148 /* Encode via the codec registry */
3149 v = PyCodec_Encode(unicode, encoding, errors);
3150 if (v == NULL)
3151 goto onError;
3152 return v;
3153
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003155 return NULL;
3156}
3157
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003158static size_t
3159wcstombs_errorpos(const wchar_t *wstr)
3160{
3161 size_t len;
3162#if SIZEOF_WCHAR_T == 2
3163 wchar_t buf[3];
3164#else
3165 wchar_t buf[2];
3166#endif
3167 char outbuf[MB_LEN_MAX];
3168 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003169
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003170#if SIZEOF_WCHAR_T == 2
3171 buf[2] = 0;
3172#else
3173 buf[1] = 0;
3174#endif
3175 start = wstr;
3176 while (*wstr != L'\0')
3177 {
3178 previous = wstr;
3179#if SIZEOF_WCHAR_T == 2
3180 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3181 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3182 {
3183 buf[0] = wstr[0];
3184 buf[1] = wstr[1];
3185 wstr += 2;
3186 }
3187 else {
3188 buf[0] = *wstr;
3189 buf[1] = 0;
3190 wstr++;
3191 }
3192#else
3193 buf[0] = *wstr;
3194 wstr++;
3195#endif
3196 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003197 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003199 }
3200
3201 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003202 return 0;
3203}
3204
Victor Stinner1b579672011-12-17 05:47:23 +01003205static int
3206locale_error_handler(const char *errors, int *surrogateescape)
3207{
3208 if (errors == NULL) {
3209 *surrogateescape = 0;
3210 return 0;
3211 }
3212
3213 if (strcmp(errors, "strict") == 0) {
3214 *surrogateescape = 0;
3215 return 0;
3216 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003217 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003218 *surrogateescape = 1;
3219 return 0;
3220 }
3221 PyErr_Format(PyExc_ValueError,
3222 "only 'strict' and 'surrogateescape' error handlers "
3223 "are supported, not '%s'",
3224 errors);
3225 return -1;
3226}
3227
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003228PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003229PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003230{
3231 Py_ssize_t wlen, wlen2;
3232 wchar_t *wstr;
3233 PyObject *bytes = NULL;
3234 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003235 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236 PyObject *exc;
3237 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003238 int surrogateescape;
3239
3240 if (locale_error_handler(errors, &surrogateescape) < 0)
3241 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003242
3243 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3244 if (wstr == NULL)
3245 return NULL;
3246
3247 wlen2 = wcslen(wstr);
3248 if (wlen2 != wlen) {
3249 PyMem_Free(wstr);
3250 PyErr_SetString(PyExc_TypeError, "embedded null character");
3251 return NULL;
3252 }
3253
3254 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003255 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003256 char *str;
3257
3258 str = _Py_wchar2char(wstr, &error_pos);
3259 if (str == NULL) {
3260 if (error_pos == (size_t)-1) {
3261 PyErr_NoMemory();
3262 PyMem_Free(wstr);
3263 return NULL;
3264 }
3265 else {
3266 goto encode_error;
3267 }
3268 }
3269 PyMem_Free(wstr);
3270
3271 bytes = PyBytes_FromString(str);
3272 PyMem_Free(str);
3273 }
3274 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003275 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003276 size_t len, len2;
3277
3278 len = wcstombs(NULL, wstr, 0);
3279 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003280 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003281 goto encode_error;
3282 }
3283
3284 bytes = PyBytes_FromStringAndSize(NULL, len);
3285 if (bytes == NULL) {
3286 PyMem_Free(wstr);
3287 return NULL;
3288 }
3289
3290 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3291 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003292 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 goto encode_error;
3294 }
3295 PyMem_Free(wstr);
3296 }
3297 return bytes;
3298
3299encode_error:
3300 errmsg = strerror(errno);
3301 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003302
3303 if (error_pos == (size_t)-1)
3304 error_pos = wcstombs_errorpos(wstr);
3305
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003306 PyMem_Free(wstr);
3307 Py_XDECREF(bytes);
3308
Victor Stinner2f197072011-12-17 07:08:30 +01003309 if (errmsg != NULL) {
3310 size_t errlen;
3311 wstr = _Py_char2wchar(errmsg, &errlen);
3312 if (wstr != NULL) {
3313 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003314 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003315 } else
3316 errmsg = NULL;
3317 }
3318 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003319 reason = PyUnicode_FromString(
3320 "wcstombs() encountered an unencodable "
3321 "wide character");
3322 if (reason == NULL)
3323 return NULL;
3324
3325 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3326 "locale", unicode,
3327 (Py_ssize_t)error_pos,
3328 (Py_ssize_t)(error_pos+1),
3329 reason);
3330 Py_DECREF(reason);
3331 if (exc != NULL) {
3332 PyCodec_StrictErrors(exc);
3333 Py_XDECREF(exc);
3334 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003335 return NULL;
3336}
3337
Victor Stinnerad158722010-10-27 00:25:46 +00003338PyObject *
3339PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003340{
Victor Stinner99b95382011-07-04 14:23:54 +02003341#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003342 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003343#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003344 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003345#else
Victor Stinner793b5312011-04-27 00:24:21 +02003346 PyInterpreterState *interp = PyThreadState_GET()->interp;
3347 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3348 cannot use it to encode and decode filenames before it is loaded. Load
3349 the Python codec requires to encode at least its own filename. Use the C
3350 version of the locale codec until the codec registry is initialized and
3351 the Python codec is loaded.
3352
3353 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3354 cannot only rely on it: check also interp->fscodec_initialized for
3355 subinterpreters. */
3356 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003357 return PyUnicode_AsEncodedString(unicode,
3358 Py_FileSystemDefaultEncoding,
3359 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003360 }
3361 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003362 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003363 }
Victor Stinnerad158722010-10-27 00:25:46 +00003364#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003365}
3366
Alexander Belopolsky40018472011-02-26 01:02:56 +00003367PyObject *
3368PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003369 const char *encoding,
3370 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003371{
3372 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003373 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003374
Guido van Rossumd57fd912000-03-10 22:53:23 +00003375 if (!PyUnicode_Check(unicode)) {
3376 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003378 }
Fred Drakee4315f52000-05-09 19:53:39 +00003379
Fred Drakee4315f52000-05-09 19:53:39 +00003380 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003381 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003382 if ((strcmp(lower, "utf-8") == 0) ||
3383 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003384 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003385 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003387 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003389 }
Victor Stinner37296e82010-06-10 13:36:23 +00003390 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003391 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003392 (strcmp(lower, "iso-8859-1") == 0) ||
3393 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003395#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003396 else if (strcmp(lower, "mbcs") == 0)
3397 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003398#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003399 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003402
3403 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003404 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003405 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003406 return NULL;
3407
3408 /* The normal path */
3409 if (PyBytes_Check(v))
3410 return v;
3411
3412 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003414 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003415 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003416
3417 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003418 "encoder %s returned bytearray instead of bytes; "
3419 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003420 encoding);
3421 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003422 Py_DECREF(v);
3423 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003425
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003426 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3427 Py_DECREF(v);
3428 return b;
3429 }
3430
3431 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003432 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3433 "use codecs.encode() to encode to arbitrary types",
3434 encoding,
3435 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003436 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003437 return NULL;
3438}
3439
Alexander Belopolsky40018472011-02-26 01:02:56 +00003440PyObject *
3441PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003442 const char *encoding,
3443 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003444{
3445 PyObject *v;
3446
3447 if (!PyUnicode_Check(unicode)) {
3448 PyErr_BadArgument();
3449 goto onError;
3450 }
3451
3452 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003453 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003454
3455 /* Encode via the codec registry */
3456 v = PyCodec_Encode(unicode, encoding, errors);
3457 if (v == NULL)
3458 goto onError;
3459 if (!PyUnicode_Check(v)) {
3460 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003461 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3462 "use codecs.encode() to encode to arbitrary types",
3463 encoding,
3464 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003465 Py_DECREF(v);
3466 goto onError;
3467 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003468 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003469
Benjamin Peterson29060642009-01-31 22:14:21 +00003470 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003471 return NULL;
3472}
3473
Victor Stinner2f197072011-12-17 07:08:30 +01003474static size_t
3475mbstowcs_errorpos(const char *str, size_t len)
3476{
3477#ifdef HAVE_MBRTOWC
3478 const char *start = str;
3479 mbstate_t mbs;
3480 size_t converted;
3481 wchar_t ch;
3482
3483 memset(&mbs, 0, sizeof mbs);
3484 while (len)
3485 {
3486 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3487 if (converted == 0)
3488 /* Reached end of string */
3489 break;
3490 if (converted == (size_t)-1 || converted == (size_t)-2) {
3491 /* Conversion error or incomplete character */
3492 return str - start;
3493 }
3494 else {
3495 str += converted;
3496 len -= converted;
3497 }
3498 }
3499 /* failed to find the undecodable byte sequence */
3500 return 0;
3501#endif
3502 return 0;
3503}
3504
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003505PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003507 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003508{
3509 wchar_t smallbuf[256];
3510 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3511 wchar_t *wstr;
3512 size_t wlen, wlen2;
3513 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003514 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003515 size_t error_pos;
3516 char *errmsg;
3517 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003518
3519 if (locale_error_handler(errors, &surrogateescape) < 0)
3520 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003521
3522 if (str[len] != '\0' || len != strlen(str)) {
3523 PyErr_SetString(PyExc_TypeError, "embedded null character");
3524 return NULL;
3525 }
3526
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003527 if (surrogateescape) {
3528 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003529 wstr = _Py_char2wchar(str, &wlen);
3530 if (wstr == NULL) {
3531 if (wlen == (size_t)-1)
3532 PyErr_NoMemory();
3533 else
3534 PyErr_SetFromErrno(PyExc_OSError);
3535 return NULL;
3536 }
3537
3538 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003539 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003540 }
3541 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003542 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003543#ifndef HAVE_BROKEN_MBSTOWCS
3544 wlen = mbstowcs(NULL, str, 0);
3545#else
3546 wlen = len;
3547#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003548 if (wlen == (size_t)-1)
3549 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003550 if (wlen+1 <= smallbuf_len) {
3551 wstr = smallbuf;
3552 }
3553 else {
3554 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3555 return PyErr_NoMemory();
3556
3557 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3558 if (!wstr)
3559 return PyErr_NoMemory();
3560 }
3561
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003562 wlen2 = mbstowcs(wstr, str, wlen+1);
3563 if (wlen2 == (size_t)-1) {
3564 if (wstr != smallbuf)
3565 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003566 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003567 }
3568#ifdef HAVE_BROKEN_MBSTOWCS
3569 assert(wlen2 == wlen);
3570#endif
3571 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3572 if (wstr != smallbuf)
3573 PyMem_Free(wstr);
3574 }
3575 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003576
3577decode_error:
3578 errmsg = strerror(errno);
3579 assert(errmsg != NULL);
3580
3581 error_pos = mbstowcs_errorpos(str, len);
3582 if (errmsg != NULL) {
3583 size_t errlen;
3584 wstr = _Py_char2wchar(errmsg, &errlen);
3585 if (wstr != NULL) {
3586 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003587 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003588 } else
3589 errmsg = NULL;
3590 }
3591 if (errmsg == NULL)
3592 reason = PyUnicode_FromString(
3593 "mbstowcs() encountered an invalid multibyte sequence");
3594 if (reason == NULL)
3595 return NULL;
3596
3597 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3598 "locale", str, len,
3599 (Py_ssize_t)error_pos,
3600 (Py_ssize_t)(error_pos+1),
3601 reason);
3602 Py_DECREF(reason);
3603 if (exc != NULL) {
3604 PyCodec_StrictErrors(exc);
3605 Py_XDECREF(exc);
3606 }
3607 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003608}
3609
3610PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003611PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003612{
3613 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003614 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003615}
3616
3617
3618PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003619PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003621 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3622}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623
Christian Heimes5894ba72007-11-04 11:43:14 +00003624PyObject*
3625PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3626{
Victor Stinner99b95382011-07-04 14:23:54 +02003627#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003628 return PyUnicode_DecodeMBCS(s, size, NULL);
3629#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003630 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003631#else
Victor Stinner793b5312011-04-27 00:24:21 +02003632 PyInterpreterState *interp = PyThreadState_GET()->interp;
3633 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3634 cannot use it to encode and decode filenames before it is loaded. Load
3635 the Python codec requires to encode at least its own filename. Use the C
3636 version of the locale codec until the codec registry is initialized and
3637 the Python codec is loaded.
3638
3639 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3640 cannot only rely on it: check also interp->fscodec_initialized for
3641 subinterpreters. */
3642 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003643 return PyUnicode_Decode(s, size,
3644 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003645 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003646 }
3647 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003648 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003649 }
Victor Stinnerad158722010-10-27 00:25:46 +00003650#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003651}
3652
Martin v. Löwis011e8422009-05-05 04:43:17 +00003653
3654int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003655_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003656{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003657 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003658
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003659 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003660 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003661 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3662 PyUnicode_GET_LENGTH(str), '\0', 1);
3663 if (pos == -1)
3664 return 0;
3665 else
3666 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003667}
3668
Antoine Pitrou13348842012-01-29 18:36:34 +01003669int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003670PyUnicode_FSConverter(PyObject* arg, void* addr)
3671{
3672 PyObject *output = NULL;
3673 Py_ssize_t size;
3674 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 if (arg == NULL) {
3676 Py_DECREF(*(PyObject**)addr);
3677 return 1;
3678 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003679 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003680 output = arg;
3681 Py_INCREF(output);
3682 }
3683 else {
3684 arg = PyUnicode_FromObject(arg);
3685 if (!arg)
3686 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003687 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003688 Py_DECREF(arg);
3689 if (!output)
3690 return 0;
3691 if (!PyBytes_Check(output)) {
3692 Py_DECREF(output);
3693 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3694 return 0;
3695 }
3696 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003697 size = PyBytes_GET_SIZE(output);
3698 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003699 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003700 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003701 Py_DECREF(output);
3702 return 0;
3703 }
3704 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003705 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003706}
3707
3708
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003709int
3710PyUnicode_FSDecoder(PyObject* arg, void* addr)
3711{
3712 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003713 if (arg == NULL) {
3714 Py_DECREF(*(PyObject**)addr);
3715 return 1;
3716 }
3717 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003718 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 output = arg;
3721 Py_INCREF(output);
3722 }
3723 else {
3724 arg = PyBytes_FromObject(arg);
3725 if (!arg)
3726 return 0;
3727 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3728 PyBytes_GET_SIZE(arg));
3729 Py_DECREF(arg);
3730 if (!output)
3731 return 0;
3732 if (!PyUnicode_Check(output)) {
3733 Py_DECREF(output);
3734 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3735 return 0;
3736 }
3737 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003738 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003739 Py_DECREF(output);
3740 return 0;
3741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003743 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003744 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3745 Py_DECREF(output);
3746 return 0;
3747 }
3748 *(PyObject**)addr = output;
3749 return Py_CLEANUP_SUPPORTED;
3750}
3751
3752
Martin v. Löwis5b222132007-06-10 09:51:05 +00003753char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003754PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003755{
Christian Heimesf3863112007-11-22 07:46:41 +00003756 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003757
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003758 if (!PyUnicode_Check(unicode)) {
3759 PyErr_BadArgument();
3760 return NULL;
3761 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003762 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003763 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003765 if (PyUnicode_UTF8(unicode) == NULL) {
3766 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3768 if (bytes == NULL)
3769 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003770 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3771 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003772 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 Py_DECREF(bytes);
3774 return NULL;
3775 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003776 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3777 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3778 PyBytes_AS_STRING(bytes),
3779 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 Py_DECREF(bytes);
3781 }
3782
3783 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003784 *psize = PyUnicode_UTF8_LENGTH(unicode);
3785 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003786}
3787
3788char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3792}
3793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003794Py_UNICODE *
3795PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003797 const unsigned char *one_byte;
3798#if SIZEOF_WCHAR_T == 4
3799 const Py_UCS2 *two_bytes;
3800#else
3801 const Py_UCS4 *four_bytes;
3802 const Py_UCS4 *ucs4_end;
3803 Py_ssize_t num_surrogates;
3804#endif
3805 wchar_t *w;
3806 wchar_t *wchar_end;
3807
3808 if (!PyUnicode_Check(unicode)) {
3809 PyErr_BadArgument();
3810 return NULL;
3811 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003812 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003813 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 assert(_PyUnicode_KIND(unicode) != 0);
3815 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003816
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003817 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3820 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821 num_surrogates = 0;
3822
3823 for (; four_bytes < ucs4_end; ++four_bytes) {
3824 if (*four_bytes > 0xFFFF)
3825 ++num_surrogates;
3826 }
3827
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003828 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3829 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3830 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003831 PyErr_NoMemory();
3832 return NULL;
3833 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003834 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003835
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003836 w = _PyUnicode_WSTR(unicode);
3837 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3838 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3840 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003841 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003842 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003843 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3844 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 }
3846 else
3847 *w = *four_bytes;
3848
3849 if (w > wchar_end) {
3850 assert(0 && "Miscalculated string end");
3851 }
3852 }
3853 *w = 0;
3854#else
3855 /* sizeof(wchar_t) == 4 */
3856 Py_FatalError("Impossible unicode object state, wstr and str "
3857 "should share memory already.");
3858 return NULL;
3859#endif
3860 }
3861 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3863 (_PyUnicode_LENGTH(unicode) + 1));
3864 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865 PyErr_NoMemory();
3866 return NULL;
3867 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003868 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3869 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3870 w = _PyUnicode_WSTR(unicode);
3871 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3874 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 for (; w < wchar_end; ++one_byte, ++w)
3876 *w = *one_byte;
3877 /* null-terminate the wstr */
3878 *w = 0;
3879 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003880 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003883 for (; w < wchar_end; ++two_bytes, ++w)
3884 *w = *two_bytes;
3885 /* null-terminate the wstr */
3886 *w = 0;
3887#else
3888 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003889 PyObject_FREE(_PyUnicode_WSTR(unicode));
3890 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003891 Py_FatalError("Impossible unicode object state, wstr "
3892 "and str should share memory already.");
3893 return NULL;
3894#endif
3895 }
3896 else {
3897 assert(0 && "This should never happen.");
3898 }
3899 }
3900 }
3901 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003902 *size = PyUnicode_WSTR_LENGTH(unicode);
3903 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003904}
3905
Alexander Belopolsky40018472011-02-26 01:02:56 +00003906Py_UNICODE *
3907PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003910}
3911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Alexander Belopolsky40018472011-02-26 01:02:56 +00003913Py_ssize_t
3914PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003915{
3916 if (!PyUnicode_Check(unicode)) {
3917 PyErr_BadArgument();
3918 goto onError;
3919 }
3920 return PyUnicode_GET_SIZE(unicode);
3921
Benjamin Peterson29060642009-01-31 22:14:21 +00003922 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003923 return -1;
3924}
3925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926Py_ssize_t
3927PyUnicode_GetLength(PyObject *unicode)
3928{
Victor Stinner07621332012-06-16 04:53:46 +02003929 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 PyErr_BadArgument();
3931 return -1;
3932 }
Victor Stinner07621332012-06-16 04:53:46 +02003933 if (PyUnicode_READY(unicode) == -1)
3934 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003935 return PyUnicode_GET_LENGTH(unicode);
3936}
3937
3938Py_UCS4
3939PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3940{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003941 void *data;
3942 int kind;
3943
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003944 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3945 PyErr_BadArgument();
3946 return (Py_UCS4)-1;
3947 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003948 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003949 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 return (Py_UCS4)-1;
3951 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003952 data = PyUnicode_DATA(unicode);
3953 kind = PyUnicode_KIND(unicode);
3954 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003955}
3956
3957int
3958PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3959{
3960 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003961 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003962 return -1;
3963 }
Victor Stinner488fa492011-12-12 00:01:39 +01003964 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003965 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003966 PyErr_SetString(PyExc_IndexError, "string index out of range");
3967 return -1;
3968 }
Victor Stinner488fa492011-12-12 00:01:39 +01003969 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003970 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003971 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3972 PyErr_SetString(PyExc_ValueError, "character out of range");
3973 return -1;
3974 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3976 index, ch);
3977 return 0;
3978}
3979
Alexander Belopolsky40018472011-02-26 01:02:56 +00003980const char *
3981PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003982{
Victor Stinner42cb4622010-09-01 19:39:01 +00003983 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003984}
3985
Victor Stinner554f3f02010-06-16 23:33:54 +00003986/* create or adjust a UnicodeDecodeError */
3987static void
3988make_decode_exception(PyObject **exceptionObject,
3989 const char *encoding,
3990 const char *input, Py_ssize_t length,
3991 Py_ssize_t startpos, Py_ssize_t endpos,
3992 const char *reason)
3993{
3994 if (*exceptionObject == NULL) {
3995 *exceptionObject = PyUnicodeDecodeError_Create(
3996 encoding, input, length, startpos, endpos, reason);
3997 }
3998 else {
3999 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4000 goto onError;
4001 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4002 goto onError;
4003 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4004 goto onError;
4005 }
4006 return;
4007
4008onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004009 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004010}
4011
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013/* error handling callback helper:
4014 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004015 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 and adjust various state variables.
4017 return 0 on success, -1 on error
4018*/
4019
Alexander Belopolsky40018472011-02-26 01:02:56 +00004020static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004021unicode_decode_call_errorhandler_wchar(
4022 const char *errors, PyObject **errorHandler,
4023 const char *encoding, const char *reason,
4024 const char **input, const char **inend, Py_ssize_t *startinpos,
4025 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4026 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004027{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004028 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004029
4030 PyObject *restuple = NULL;
4031 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004032 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004033 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004034 Py_ssize_t requiredsize;
4035 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004036 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004037 wchar_t *repwstr;
4038 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004040 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4041 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 *errorHandler = PyCodec_LookupError(errors);
4045 if (*errorHandler == NULL)
4046 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004047 }
4048
Victor Stinner554f3f02010-06-16 23:33:54 +00004049 make_decode_exception(exceptionObject,
4050 encoding,
4051 *input, *inend - *input,
4052 *startinpos, *endinpos,
4053 reason);
4054 if (*exceptionObject == NULL)
4055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056
4057 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4058 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004059 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004061 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004062 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 }
4064 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004066
4067 /* Copy back the bytes variables, which might have been modified by the
4068 callback */
4069 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4070 if (!inputobj)
4071 goto onError;
4072 if (!PyBytes_Check(inputobj)) {
4073 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4074 }
4075 *input = PyBytes_AS_STRING(inputobj);
4076 insize = PyBytes_GET_SIZE(inputobj);
4077 *inend = *input + insize;
4078 /* we can DECREF safely, as the exception has another reference,
4079 so the object won't go away. */
4080 Py_DECREF(inputobj);
4081
4082 if (newpos<0)
4083 newpos = insize+newpos;
4084 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004085 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 goto onError;
4087 }
4088
4089 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4090 if (repwstr == NULL)
4091 goto onError;
4092 /* need more space? (at least enough for what we
4093 have+the replacement+the rest of the string (starting
4094 at the new input position), so we won't have to check space
4095 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004096 requiredsize = *outpos;
4097 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4098 goto overflow;
4099 requiredsize += repwlen;
4100 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4101 goto overflow;
4102 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004103 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004104 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004105 requiredsize = 2*outsize;
4106 if (unicode_resize(output, requiredsize) < 0)
4107 goto onError;
4108 }
4109 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4110 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004111 *endinpos = newpos;
4112 *inptr = *input + newpos;
4113
4114 /* we made it! */
4115 Py_XDECREF(restuple);
4116 return 0;
4117
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004118 overflow:
4119 PyErr_SetString(PyExc_OverflowError,
4120 "decoded result is too long for a Python string");
4121
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004122 onError:
4123 Py_XDECREF(restuple);
4124 return -1;
4125}
4126#endif /* HAVE_MBCS */
4127
4128static int
4129unicode_decode_call_errorhandler_writer(
4130 const char *errors, PyObject **errorHandler,
4131 const char *encoding, const char *reason,
4132 const char **input, const char **inend, Py_ssize_t *startinpos,
4133 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4134 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4135{
4136 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4137
4138 PyObject *restuple = NULL;
4139 PyObject *repunicode = NULL;
4140 Py_ssize_t insize;
4141 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004142 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004143 PyObject *inputobj = NULL;
4144
4145 if (*errorHandler == NULL) {
4146 *errorHandler = PyCodec_LookupError(errors);
4147 if (*errorHandler == NULL)
4148 goto onError;
4149 }
4150
4151 make_decode_exception(exceptionObject,
4152 encoding,
4153 *input, *inend - *input,
4154 *startinpos, *endinpos,
4155 reason);
4156 if (*exceptionObject == NULL)
4157 goto onError;
4158
4159 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4160 if (restuple == NULL)
4161 goto onError;
4162 if (!PyTuple_Check(restuple)) {
4163 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4164 goto onError;
4165 }
4166 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004167 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004168
4169 /* Copy back the bytes variables, which might have been modified by the
4170 callback */
4171 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4172 if (!inputobj)
4173 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004174 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004175 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004176 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004177 *input = PyBytes_AS_STRING(inputobj);
4178 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004179 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004180 /* we can DECREF safely, as the exception has another reference,
4181 so the object won't go away. */
4182 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004183
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004184 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004185 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004186 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004187 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004188 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004189 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004190
Victor Stinner8f674cc2013-04-17 23:02:17 +02004191 if (PyUnicode_READY(repunicode) < 0)
4192 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004193 replen = PyUnicode_GET_LENGTH(repunicode);
4194 writer->min_length += replen;
4195 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004196 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004197 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004198 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004199
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004201 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004202
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004204 Py_XDECREF(restuple);
4205 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004206
Benjamin Peterson29060642009-01-31 22:14:21 +00004207 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004208 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004209 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004210}
4211
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004212/* --- UTF-7 Codec -------------------------------------------------------- */
4213
Antoine Pitrou244651a2009-05-04 18:56:13 +00004214/* See RFC2152 for details. We encode conservatively and decode liberally. */
4215
4216/* Three simple macros defining base-64. */
4217
4218/* Is c a base-64 character? */
4219
4220#define IS_BASE64(c) \
4221 (((c) >= 'A' && (c) <= 'Z') || \
4222 ((c) >= 'a' && (c) <= 'z') || \
4223 ((c) >= '0' && (c) <= '9') || \
4224 (c) == '+' || (c) == '/')
4225
4226/* given that c is a base-64 character, what is its base-64 value? */
4227
4228#define FROM_BASE64(c) \
4229 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4230 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4231 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4232 (c) == '+' ? 62 : 63)
4233
4234/* What is the base-64 character of the bottom 6 bits of n? */
4235
4236#define TO_BASE64(n) \
4237 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4238
4239/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4240 * decoded as itself. We are permissive on decoding; the only ASCII
4241 * byte not decoding to itself is the + which begins a base64
4242 * string. */
4243
4244#define DECODE_DIRECT(c) \
4245 ((c) <= 127 && (c) != '+')
4246
4247/* The UTF-7 encoder treats ASCII characters differently according to
4248 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4249 * the above). See RFC2152. This array identifies these different
4250 * sets:
4251 * 0 : "Set D"
4252 * alphanumeric and '(),-./:?
4253 * 1 : "Set O"
4254 * !"#$%&*;<=>@[]^_`{|}
4255 * 2 : "whitespace"
4256 * ht nl cr sp
4257 * 3 : special (must be base64 encoded)
4258 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4259 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004260
Tim Petersced69f82003-09-16 20:30:58 +00004261static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004262char utf7_category[128] = {
4263/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4264 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4265/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4266 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4267/* sp ! " # $ % & ' ( ) * + , - . / */
4268 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4269/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4271/* @ A B C D E F G H I J K L M N O */
4272 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4273/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4275/* ` a b c d e f g h i j k l m n o */
4276 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4277/* p q r s t u v w x y z { | } ~ del */
4278 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004279};
4280
Antoine Pitrou244651a2009-05-04 18:56:13 +00004281/* ENCODE_DIRECT: this character should be encoded as itself. The
4282 * answer depends on whether we are encoding set O as itself, and also
4283 * on whether we are encoding whitespace as itself. RFC2152 makes it
4284 * clear that the answers to these questions vary between
4285 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004286
Antoine Pitrou244651a2009-05-04 18:56:13 +00004287#define ENCODE_DIRECT(c, directO, directWS) \
4288 ((c) < 128 && (c) > 0 && \
4289 ((utf7_category[(c)] == 0) || \
4290 (directWS && (utf7_category[(c)] == 2)) || \
4291 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004292
Alexander Belopolsky40018472011-02-26 01:02:56 +00004293PyObject *
4294PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004295 Py_ssize_t size,
4296 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004297{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004298 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4299}
4300
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301/* The decoder. The only state we preserve is our read position,
4302 * i.e. how many characters we have consumed. So if we end in the
4303 * middle of a shift sequence we have to back off the read position
4304 * and the output to the beginning of the sequence, otherwise we lose
4305 * all the shift state (seen bits, number of bits seen, high
4306 * surrogate). */
4307
Alexander Belopolsky40018472011-02-26 01:02:56 +00004308PyObject *
4309PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004310 Py_ssize_t size,
4311 const char *errors,
4312 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004313{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004315 Py_ssize_t startinpos;
4316 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004317 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004318 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 const char *errmsg = "";
4320 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004322 unsigned int base64bits = 0;
4323 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004324 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004325 PyObject *errorHandler = NULL;
4326 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004328 if (size == 0) {
4329 if (consumed)
4330 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004331 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004332 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004335 _PyUnicodeWriter_Init(&writer);
4336 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004337
4338 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339 e = s + size;
4340
4341 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004344 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 if (inShift) { /* in a base-64 section */
4347 if (IS_BASE64(ch)) { /* consume a base-64 character */
4348 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4349 base64bits += 6;
4350 s++;
4351 if (base64bits >= 16) {
4352 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004353 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 base64bits -= 16;
4355 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004356 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 if (surrogate) {
4358 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004359 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4360 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004361 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004364 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 }
4366 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004367 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004368 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
Victor Stinner551ac952011-11-29 22:58:13 +01004372 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 /* first surrogate */
4374 surrogate = outCh;
4375 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004378 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 }
4380 }
4381 }
4382 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 inShift = 0;
4384 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004386 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004387 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004388 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004390 if (base64bits > 0) { /* left-over bits */
4391 if (base64bits >= 6) {
4392 /* We've seen at least one base-64 character */
4393 errmsg = "partial character in shift sequence";
4394 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004396 else {
4397 /* Some bits remain; they should be zero */
4398 if (base64buffer != 0) {
4399 errmsg = "non-zero padding bits in shift sequence";
4400 goto utf7Error;
4401 }
4402 }
4403 }
4404 if (ch != '-') {
4405 /* '-' is absorbed; other terminating
4406 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004407 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
4411 }
4412 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 s++; /* consume '+' */
4415 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004417 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 }
4420 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004422 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004424 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425 }
4426 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004428 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004429 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004430 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004431 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 else {
4433 startinpos = s-starts;
4434 s++;
4435 errmsg = "unexpected special character";
4436 goto utf7Error;
4437 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004440 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004441 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 errors, &errorHandler,
4443 "utf7", errmsg,
4444 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004445 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004446 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447 }
4448
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 /* end of string */
4450
4451 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4452 /* if we're in an inconsistent state, that's an error */
4453 if (surrogate ||
4454 (base64bits >= 6) ||
4455 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004457 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458 errors, &errorHandler,
4459 "utf7", "unterminated shift sequence",
4460 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004461 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 goto onError;
4463 if (s < e)
4464 goto restart;
4465 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467
4468 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004469 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004471 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004472 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004473 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004474 writer.kind, writer.data, shiftOutStart);
4475 Py_XDECREF(errorHandler);
4476 Py_XDECREF(exc);
4477 _PyUnicodeWriter_Dealloc(&writer);
4478 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004479 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004480 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
4482 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004483 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004484 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004485 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004487 Py_XDECREF(errorHandler);
4488 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004489 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490
Benjamin Peterson29060642009-01-31 22:14:21 +00004491 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004492 Py_XDECREF(errorHandler);
4493 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004494 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495 return NULL;
4496}
4497
4498
Alexander Belopolsky40018472011-02-26 01:02:56 +00004499PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004500_PyUnicode_EncodeUTF7(PyObject *str,
4501 int base64SetO,
4502 int base64WhiteSpace,
4503 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004504{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004505 int kind;
4506 void *data;
4507 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004508 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004509 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004510 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004511 unsigned int base64bits = 0;
4512 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513 char * out;
4514 char * start;
4515
Benjamin Petersonbac79492012-01-14 13:34:47 -05004516 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004517 return NULL;
4518 kind = PyUnicode_KIND(str);
4519 data = PyUnicode_DATA(str);
4520 len = PyUnicode_GET_LENGTH(str);
4521
4522 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004523 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004525 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004526 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004527 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004528 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004529 if (v == NULL)
4530 return NULL;
4531
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004532 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004533 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004534 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536 if (inShift) {
4537 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4538 /* shifting out */
4539 if (base64bits) { /* output remaining bits */
4540 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4541 base64buffer = 0;
4542 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004543 }
4544 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004545 /* Characters not in the BASE64 set implicitly unshift the sequence
4546 so no '-' is required, except if the character is itself a '-' */
4547 if (IS_BASE64(ch) || ch == '-') {
4548 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004549 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004550 *out++ = (char) ch;
4551 }
4552 else {
4553 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556 else { /* not in a shift sequence */
4557 if (ch == '+') {
4558 *out++ = '+';
4559 *out++ = '-';
4560 }
4561 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4562 *out++ = (char) ch;
4563 }
4564 else {
4565 *out++ = '+';
4566 inShift = 1;
4567 goto encode_char;
4568 }
4569 }
4570 continue;
4571encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004572 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004573 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004574
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 /* code first surrogate */
4576 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004577 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 while (base64bits >= 6) {
4579 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4580 base64bits -= 6;
4581 }
4582 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004583 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004585 base64bits += 16;
4586 base64buffer = (base64buffer << 16) | ch;
4587 while (base64bits >= 6) {
4588 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4589 base64bits -= 6;
4590 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004591 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004592 if (base64bits)
4593 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4594 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004595 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004596 if (_PyBytes_Resize(&v, out - start) < 0)
4597 return NULL;
4598 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004599}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004600PyObject *
4601PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4602 Py_ssize_t size,
4603 int base64SetO,
4604 int base64WhiteSpace,
4605 const char *errors)
4606{
4607 PyObject *result;
4608 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4609 if (tmp == NULL)
4610 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004611 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004612 base64WhiteSpace, errors);
4613 Py_DECREF(tmp);
4614 return result;
4615}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004616
Antoine Pitrou244651a2009-05-04 18:56:13 +00004617#undef IS_BASE64
4618#undef FROM_BASE64
4619#undef TO_BASE64
4620#undef DECODE_DIRECT
4621#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004622
Guido van Rossumd57fd912000-03-10 22:53:23 +00004623/* --- UTF-8 Codec -------------------------------------------------------- */
4624
Alexander Belopolsky40018472011-02-26 01:02:56 +00004625PyObject *
4626PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004627 Py_ssize_t size,
4628 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004629{
Walter Dörwald69652032004-09-07 20:24:22 +00004630 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4631}
4632
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004633#include "stringlib/asciilib.h"
4634#include "stringlib/codecs.h"
4635#include "stringlib/undef.h"
4636
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004637#include "stringlib/ucs1lib.h"
4638#include "stringlib/codecs.h"
4639#include "stringlib/undef.h"
4640
4641#include "stringlib/ucs2lib.h"
4642#include "stringlib/codecs.h"
4643#include "stringlib/undef.h"
4644
4645#include "stringlib/ucs4lib.h"
4646#include "stringlib/codecs.h"
4647#include "stringlib/undef.h"
4648
Antoine Pitrouab868312009-01-10 15:40:25 +00004649/* Mask to quickly check whether a C 'long' contains a
4650 non-ASCII, UTF8-encoded char. */
4651#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004652# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004653#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004654# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004655#else
4656# error C 'long' size should be either 4 or 8!
4657#endif
4658
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004659static Py_ssize_t
4660ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004661{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004662 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004663 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004664
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004665 /*
4666 * Issue #17237: m68k is a bit different from most architectures in
4667 * that objects do not use "natural alignment" - for example, int and
4668 * long are only aligned at 2-byte boundaries. Therefore the assert()
4669 * won't work; also, tests have shown that skipping the "optimised
4670 * version" will even speed up m68k.
4671 */
4672#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004673#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004674 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4675 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 /* Fast path, see in STRINGLIB(utf8_decode) for
4677 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004678 /* Help allocation */
4679 const char *_p = p;
4680 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004681 while (_p < aligned_end) {
4682 unsigned long value = *(const unsigned long *) _p;
4683 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004684 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004685 *((unsigned long *)q) = value;
4686 _p += SIZEOF_LONG;
4687 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004688 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004689 p = _p;
4690 while (p < end) {
4691 if ((unsigned char)*p & 0x80)
4692 break;
4693 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004694 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004695 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004696 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004697#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004698#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004699 while (p < end) {
4700 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4701 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004702 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004703 /* Help allocation */
4704 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004705 while (_p < aligned_end) {
4706 unsigned long value = *(unsigned long *) _p;
4707 if (value & ASCII_CHAR_MASK)
4708 break;
4709 _p += SIZEOF_LONG;
4710 }
4711 p = _p;
4712 if (_p == end)
4713 break;
4714 }
4715 if ((unsigned char)*p & 0x80)
4716 break;
4717 ++p;
4718 }
4719 memcpy(dest, start, p - start);
4720 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004721}
Antoine Pitrouab868312009-01-10 15:40:25 +00004722
Victor Stinner785938e2011-12-11 20:09:03 +01004723PyObject *
4724PyUnicode_DecodeUTF8Stateful(const char *s,
4725 Py_ssize_t size,
4726 const char *errors,
4727 Py_ssize_t *consumed)
4728{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004729 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004730 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004732
4733 Py_ssize_t startinpos;
4734 Py_ssize_t endinpos;
4735 const char *errmsg = "";
4736 PyObject *errorHandler = NULL;
4737 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004738
4739 if (size == 0) {
4740 if (consumed)
4741 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004742 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004743 }
4744
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4746 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004747 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 *consumed = 1;
4749 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004750 }
4751
Victor Stinner8f674cc2013-04-17 23:02:17 +02004752 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004753 writer.min_length = size;
4754 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004755 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004756
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 writer.pos = ascii_decode(s, end, writer.data);
4758 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004759 while (s < end) {
4760 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004761 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004762 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004763 if (PyUnicode_IS_ASCII(writer.buffer))
4764 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004766 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004768 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 } else {
4770 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004771 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004772 }
4773
4774 switch (ch) {
4775 case 0:
4776 if (s == end || consumed)
4777 goto End;
4778 errmsg = "unexpected end of data";
4779 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004780 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004781 break;
4782 case 1:
4783 errmsg = "invalid start byte";
4784 startinpos = s - starts;
4785 endinpos = startinpos + 1;
4786 break;
4787 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004788 case 3:
4789 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004790 errmsg = "invalid continuation byte";
4791 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004792 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004793 break;
4794 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004795 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004796 goto onError;
4797 continue;
4798 }
4799
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004800 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801 errors, &errorHandler,
4802 "utf-8", errmsg,
4803 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004804 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004806 }
4807
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004808End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004809 if (consumed)
4810 *consumed = s - starts;
4811
4812 Py_XDECREF(errorHandler);
4813 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004814 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815
4816onError:
4817 Py_XDECREF(errorHandler);
4818 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004819 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004820 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004821}
4822
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004823#ifdef __APPLE__
4824
4825/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004826 used to decode the command line arguments on Mac OS X.
4827
4828 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004829 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004830
4831wchar_t*
4832_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4833{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 wchar_t *unicode;
4836 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004837
4838 /* Note: size will always be longer than the resulting Unicode
4839 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004840 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004841 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004842 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843 if (!unicode)
4844 return NULL;
4845
4846 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004847 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004848 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004851#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004853#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004854 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 if (ch > 0xFF) {
4857#if SIZEOF_WCHAR_T == 4
4858 assert(0);
4859#else
4860 assert(Py_UNICODE_IS_SURROGATE(ch));
4861 /* compute and append the two surrogates: */
4862 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4863 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4864#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004865 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 else {
4867 if (!ch && s == e)
4868 break;
4869 /* surrogateescape */
4870 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4871 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004872 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004873 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004874 return unicode;
4875}
4876
4877#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004878
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004879/* Primary internal function which creates utf8 encoded bytes objects.
4880
4881 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004882 and allocate exactly as much space needed at the end. Else allocate the
4883 maximum possible needed (4 result bytes per Unicode character), and return
4884 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004885*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004886PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004887_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004888{
Victor Stinner6099a032011-12-18 14:22:26 +01004889 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004890 void *data;
4891 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004892
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004893 if (!PyUnicode_Check(unicode)) {
4894 PyErr_BadArgument();
4895 return NULL;
4896 }
4897
4898 if (PyUnicode_READY(unicode) == -1)
4899 return NULL;
4900
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004901 if (PyUnicode_UTF8(unicode))
4902 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4903 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004904
4905 kind = PyUnicode_KIND(unicode);
4906 data = PyUnicode_DATA(unicode);
4907 size = PyUnicode_GET_LENGTH(unicode);
4908
Benjamin Petersonead6b532011-12-20 17:23:42 -06004909 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004910 default:
4911 assert(0);
4912 case PyUnicode_1BYTE_KIND:
4913 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4914 assert(!PyUnicode_IS_ASCII(unicode));
4915 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4916 case PyUnicode_2BYTE_KIND:
4917 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4918 case PyUnicode_4BYTE_KIND:
4919 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004920 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004921}
4922
Alexander Belopolsky40018472011-02-26 01:02:56 +00004923PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004924PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4925 Py_ssize_t size,
4926 const char *errors)
4927{
4928 PyObject *v, *unicode;
4929
4930 unicode = PyUnicode_FromUnicode(s, size);
4931 if (unicode == NULL)
4932 return NULL;
4933 v = _PyUnicode_AsUTF8String(unicode, errors);
4934 Py_DECREF(unicode);
4935 return v;
4936}
4937
4938PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004939PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004940{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004941 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004942}
4943
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944/* --- UTF-32 Codec ------------------------------------------------------- */
4945
4946PyObject *
4947PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004948 Py_ssize_t size,
4949 const char *errors,
4950 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951{
4952 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4953}
4954
4955PyObject *
4956PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004957 Py_ssize_t size,
4958 const char *errors,
4959 int *byteorder,
4960 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004961{
4962 const char *starts = s;
4963 Py_ssize_t startinpos;
4964 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004965 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004966 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004967 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004968 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004970 PyObject *errorHandler = NULL;
4971 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004972
Walter Dörwald41980ca2007-08-16 21:55:45 +00004973 q = (unsigned char *)s;
4974 e = q + size;
4975
4976 if (byteorder)
4977 bo = *byteorder;
4978
4979 /* Check for BOM marks (U+FEFF) in the input and adjust current
4980 byte order setting accordingly. In native mode, the leading BOM
4981 mark is skipped, in all other modes, it is copied to the output
4982 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004983 if (bo == 0 && size >= 4) {
4984 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4985 if (bom == 0x0000FEFF) {
4986 bo = -1;
4987 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004989 else if (bom == 0xFFFE0000) {
4990 bo = 1;
4991 q += 4;
4992 }
4993 if (byteorder)
4994 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995 }
4996
Victor Stinnere64322e2012-10-30 23:12:47 +01004997 if (q == e) {
4998 if (consumed)
4999 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005000 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005001 }
5002
Victor Stinnere64322e2012-10-30 23:12:47 +01005003#ifdef WORDS_BIGENDIAN
5004 le = bo < 0;
5005#else
5006 le = bo <= 0;
5007#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005008 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005009
Victor Stinner8f674cc2013-04-17 23:02:17 +02005010 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005011 writer.min_length = (e - q + 3) / 4;
5012 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005013 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005014
Victor Stinnere64322e2012-10-30 23:12:47 +01005015 while (1) {
5016 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005017 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005018
Victor Stinnere64322e2012-10-30 23:12:47 +01005019 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005020 enum PyUnicode_Kind kind = writer.kind;
5021 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005022 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005023 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 if (le) {
5025 do {
5026 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5027 if (ch > maxch)
5028 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005029 if (kind != PyUnicode_1BYTE_KIND &&
5030 Py_UNICODE_IS_SURROGATE(ch))
5031 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005032 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005033 q += 4;
5034 } while (q <= last);
5035 }
5036 else {
5037 do {
5038 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5039 if (ch > maxch)
5040 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005041 if (kind != PyUnicode_1BYTE_KIND &&
5042 Py_UNICODE_IS_SURROGATE(ch))
5043 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005044 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005045 q += 4;
5046 } while (q <= last);
5047 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005048 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005049 }
5050
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005051 if (Py_UNICODE_IS_SURROGATE(ch)) {
5052 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5053 startinpos = ((const char *)q) - starts;
5054 endinpos = startinpos + 4;
5055 }
5056 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005057 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005058 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005059 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005061 startinpos = ((const char *)q) - starts;
5062 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005063 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005064 else {
5065 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005066 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005067 goto onError;
5068 q += 4;
5069 continue;
5070 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005071 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005072 startinpos = ((const char *)q) - starts;
5073 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005074 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005075
5076 /* The remaining input chars are ignored if the callback
5077 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005078 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005079 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005080 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005082 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084 }
5085
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005087 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089 Py_XDECREF(errorHandler);
5090 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005091 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092
Benjamin Peterson29060642009-01-31 22:14:21 +00005093 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005094 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095 Py_XDECREF(errorHandler);
5096 Py_XDECREF(exc);
5097 return NULL;
5098}
5099
5100PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005101_PyUnicode_EncodeUTF32(PyObject *str,
5102 const char *errors,
5103 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005105 int kind;
5106 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005107 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005108 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005109 unsigned char *p;
5110 Py_ssize_t nsize, i;
5111 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005112#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005113 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005114#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005115 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005116#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005117 const char *encoding;
5118 PyObject *errorHandler = NULL;
5119 PyObject *exc = NULL;
5120 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121
Serhiy Storchaka30793282014-01-04 22:44:01 +02005122#define STORECHAR(CH) \
5123 do { \
5124 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5125 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5126 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5127 p[iorder[0]] = (CH) & 0xff; \
5128 p += 4; \
5129 } while(0)
5130
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005131 if (!PyUnicode_Check(str)) {
5132 PyErr_BadArgument();
5133 return NULL;
5134 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005135 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005136 return NULL;
5137 kind = PyUnicode_KIND(str);
5138 data = PyUnicode_DATA(str);
5139 len = PyUnicode_GET_LENGTH(str);
5140
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005141 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005142 if (nsize > PY_SSIZE_T_MAX / 4)
5143 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005144 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 if (v == NULL)
5146 return NULL;
5147
Serhiy Storchaka30793282014-01-04 22:44:01 +02005148 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005149 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005150 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005151 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005152 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153
Serhiy Storchaka30793282014-01-04 22:44:01 +02005154 if (byteorder == -1) {
5155 /* force LE */
5156 iorder[0] = 0;
5157 iorder[1] = 1;
5158 iorder[2] = 2;
5159 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005160 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005161 }
5162 else if (byteorder == 1) {
5163 /* force BE */
5164 iorder[0] = 3;
5165 iorder[1] = 2;
5166 iorder[2] = 1;
5167 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005168 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005169 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005170 else
5171 encoding = "utf-32";
5172
5173 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005174 for (i = 0; i < len; i++)
5175 STORECHAR(PyUnicode_READ(kind, data, i));
5176 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005177 }
5178
Serhiy Storchaka30793282014-01-04 22:44:01 +02005179 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005181 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5182 i++;
5183 assert(ch <= MAX_UNICODE);
5184 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5185 STORECHAR(ch);
5186 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005187 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005188
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005189 rep = unicode_encode_call_errorhandler(
5190 errors, &errorHandler,
5191 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005192 str, &exc, i-1, i, &i);
5193
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005194 if (!rep)
5195 goto error;
5196
5197 if (PyBytes_Check(rep)) {
5198 repsize = PyBytes_GET_SIZE(rep);
5199 if (repsize & 3) {
5200 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005201 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005202 "surrogates not allowed");
5203 goto error;
5204 }
5205 moreunits = repsize / 4;
5206 }
5207 else {
5208 assert(PyUnicode_Check(rep));
5209 if (PyUnicode_READY(rep) < 0)
5210 goto error;
5211 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5212 if (!PyUnicode_IS_ASCII(rep)) {
5213 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005214 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005215 "surrogates not allowed");
5216 goto error;
5217 }
5218 }
5219
5220 /* four bytes are reserved for each surrogate */
5221 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005222 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005223 Py_ssize_t morebytes = 4 * (moreunits - 1);
5224 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5225 /* integer overflow */
5226 PyErr_NoMemory();
5227 goto error;
5228 }
5229 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5230 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005231 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005232 }
5233
5234 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005235 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5236 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005237 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005238 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005239 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005240 repdata = PyUnicode_1BYTE_DATA(rep);
5241 while (repsize--) {
5242 Py_UCS4 ch = *repdata++;
5243 STORECHAR(ch);
5244 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005245 }
5246
5247 Py_CLEAR(rep);
5248 }
5249
5250 /* Cut back to size actually needed. This is necessary for, for example,
5251 encoding of a string containing isolated surrogates and the 'ignore'
5252 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005253 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005254 if (nsize != PyBytes_GET_SIZE(v))
5255 _PyBytes_Resize(&v, nsize);
5256 Py_XDECREF(errorHandler);
5257 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005258 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005259 error:
5260 Py_XDECREF(rep);
5261 Py_XDECREF(errorHandler);
5262 Py_XDECREF(exc);
5263 Py_XDECREF(v);
5264 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005265#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266}
5267
Alexander Belopolsky40018472011-02-26 01:02:56 +00005268PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005269PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5270 Py_ssize_t size,
5271 const char *errors,
5272 int byteorder)
5273{
5274 PyObject *result;
5275 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5276 if (tmp == NULL)
5277 return NULL;
5278 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5279 Py_DECREF(tmp);
5280 return result;
5281}
5282
5283PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005284PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005285{
Victor Stinnerb960b342011-11-20 19:12:52 +01005286 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287}
5288
Guido van Rossumd57fd912000-03-10 22:53:23 +00005289/* --- UTF-16 Codec ------------------------------------------------------- */
5290
Tim Peters772747b2001-08-09 22:21:55 +00005291PyObject *
5292PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005293 Py_ssize_t size,
5294 const char *errors,
5295 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005296{
Walter Dörwald69652032004-09-07 20:24:22 +00005297 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5298}
5299
5300PyObject *
5301PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 Py_ssize_t size,
5303 const char *errors,
5304 int *byteorder,
5305 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005306{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005307 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005308 Py_ssize_t startinpos;
5309 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005310 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005311 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005312 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005313 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005314 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005315 PyObject *errorHandler = NULL;
5316 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005317 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005318
Tim Peters772747b2001-08-09 22:21:55 +00005319 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005320 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005321
5322 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005323 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005324
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005325 /* Check for BOM marks (U+FEFF) in the input and adjust current
5326 byte order setting accordingly. In native mode, the leading BOM
5327 mark is skipped, in all other modes, it is copied to the output
5328 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005329 if (bo == 0 && size >= 2) {
5330 const Py_UCS4 bom = (q[1] << 8) | q[0];
5331 if (bom == 0xFEFF) {
5332 q += 2;
5333 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005334 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005335 else if (bom == 0xFFFE) {
5336 q += 2;
5337 bo = 1;
5338 }
5339 if (byteorder)
5340 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005341 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005342
Antoine Pitrou63065d72012-05-15 23:48:04 +02005343 if (q == e) {
5344 if (consumed)
5345 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005346 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005347 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005348
Christian Heimes743e0cd2012-10-17 23:52:17 +02005349#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005350 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005351 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005352#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005353 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005354 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005355#endif
Tim Peters772747b2001-08-09 22:21:55 +00005356
Antoine Pitrou63065d72012-05-15 23:48:04 +02005357 /* Note: size will always be longer than the resulting Unicode
5358 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005359 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005360 writer.min_length = (e - q + 1) / 2;
5361 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363
Antoine Pitrou63065d72012-05-15 23:48:04 +02005364 while (1) {
5365 Py_UCS4 ch = 0;
5366 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005367 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005368 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005369 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005370 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005371 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005372 native_ordering);
5373 else
5374 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005376 native_ordering);
5377 } else if (kind == PyUnicode_2BYTE_KIND) {
5378 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005379 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005380 native_ordering);
5381 } else {
5382 assert(kind == PyUnicode_4BYTE_KIND);
5383 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005384 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005385 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005386 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005387 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005388
Antoine Pitrou63065d72012-05-15 23:48:04 +02005389 switch (ch)
5390 {
5391 case 0:
5392 /* remaining byte at the end? (size should be even) */
5393 if (q == e || consumed)
5394 goto End;
5395 errmsg = "truncated data";
5396 startinpos = ((const char *)q) - starts;
5397 endinpos = ((const char *)e) - starts;
5398 break;
5399 /* The remaining input chars are ignored if the callback
5400 chooses to skip the input */
5401 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005402 q -= 2;
5403 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005404 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005405 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005406 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005407 endinpos = ((const char *)e) - starts;
5408 break;
5409 case 2:
5410 errmsg = "illegal encoding";
5411 startinpos = ((const char *)q) - 2 - starts;
5412 endinpos = startinpos + 2;
5413 break;
5414 case 3:
5415 errmsg = "illegal UTF-16 surrogate";
5416 startinpos = ((const char *)q) - 4 - starts;
5417 endinpos = startinpos + 2;
5418 break;
5419 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005420 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005421 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 continue;
5423 }
5424
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005425 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005426 errors,
5427 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005428 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005429 &starts,
5430 (const char **)&e,
5431 &startinpos,
5432 &endinpos,
5433 &exc,
5434 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005435 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005436 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437 }
5438
Antoine Pitrou63065d72012-05-15 23:48:04 +02005439End:
Walter Dörwald69652032004-09-07 20:24:22 +00005440 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005441 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005442
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005443 Py_XDECREF(errorHandler);
5444 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005445 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005446
Benjamin Peterson29060642009-01-31 22:14:21 +00005447 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005448 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005449 Py_XDECREF(errorHandler);
5450 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005451 return NULL;
5452}
5453
Tim Peters772747b2001-08-09 22:21:55 +00005454PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005455_PyUnicode_EncodeUTF16(PyObject *str,
5456 const char *errors,
5457 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 enum PyUnicode_Kind kind;
5460 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005461 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005462 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005464 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005465#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005466 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005467#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005468 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005469#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005470 const char *encoding;
5471 Py_ssize_t nsize, pos;
5472 PyObject *errorHandler = NULL;
5473 PyObject *exc = NULL;
5474 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005475
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005476 if (!PyUnicode_Check(str)) {
5477 PyErr_BadArgument();
5478 return NULL;
5479 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005480 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005481 return NULL;
5482 kind = PyUnicode_KIND(str);
5483 data = PyUnicode_DATA(str);
5484 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005485
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005486 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005487 if (kind == PyUnicode_4BYTE_KIND) {
5488 const Py_UCS4 *in = (const Py_UCS4 *)data;
5489 const Py_UCS4 *end = in + len;
5490 while (in < end)
5491 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005492 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005493 }
5494 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005496 nsize = len + pairs + (byteorder == 0);
5497 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005498 if (v == NULL)
5499 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005500
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005501 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005502 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005503 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005504 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005505 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005506 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005507 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005508
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005509 if (kind == PyUnicode_1BYTE_KIND) {
5510 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5511 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005512 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005513
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005514 if (byteorder < 0)
5515 encoding = "utf-16-le";
5516 else if (byteorder > 0)
5517 encoding = "utf-16-be";
5518 else
5519 encoding = "utf-16";
5520
5521 pos = 0;
5522 while (pos < len) {
5523 Py_ssize_t repsize, moreunits;
5524
5525 if (kind == PyUnicode_2BYTE_KIND) {
5526 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5527 &out, native_ordering);
5528 }
5529 else {
5530 assert(kind == PyUnicode_4BYTE_KIND);
5531 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5532 &out, native_ordering);
5533 }
5534 if (pos == len)
5535 break;
5536
5537 rep = unicode_encode_call_errorhandler(
5538 errors, &errorHandler,
5539 encoding, "surrogates not allowed",
5540 str, &exc, pos, pos + 1, &pos);
5541 if (!rep)
5542 goto error;
5543
5544 if (PyBytes_Check(rep)) {
5545 repsize = PyBytes_GET_SIZE(rep);
5546 if (repsize & 1) {
5547 raise_encode_exception(&exc, encoding,
5548 str, pos - 1, pos,
5549 "surrogates not allowed");
5550 goto error;
5551 }
5552 moreunits = repsize / 2;
5553 }
5554 else {
5555 assert(PyUnicode_Check(rep));
5556 if (PyUnicode_READY(rep) < 0)
5557 goto error;
5558 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5559 if (!PyUnicode_IS_ASCII(rep)) {
5560 raise_encode_exception(&exc, encoding,
5561 str, pos - 1, pos,
5562 "surrogates not allowed");
5563 goto error;
5564 }
5565 }
5566
5567 /* two bytes are reserved for each surrogate */
5568 if (moreunits > 1) {
5569 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5570 Py_ssize_t morebytes = 2 * (moreunits - 1);
5571 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5572 /* integer overflow */
5573 PyErr_NoMemory();
5574 goto error;
5575 }
5576 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5577 goto error;
5578 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5579 }
5580
5581 if (PyBytes_Check(rep)) {
5582 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5583 out += moreunits;
5584 } else /* rep is unicode */ {
5585 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5586 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5587 &out, native_ordering);
5588 }
5589
5590 Py_CLEAR(rep);
5591 }
5592
5593 /* Cut back to size actually needed. This is necessary for, for example,
5594 encoding of a string containing isolated surrogates and the 'ignore' handler
5595 is used. */
5596 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5597 if (nsize != PyBytes_GET_SIZE(v))
5598 _PyBytes_Resize(&v, nsize);
5599 Py_XDECREF(errorHandler);
5600 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005601 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005602 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005603 error:
5604 Py_XDECREF(rep);
5605 Py_XDECREF(errorHandler);
5606 Py_XDECREF(exc);
5607 Py_XDECREF(v);
5608 return NULL;
5609#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005610}
5611
Alexander Belopolsky40018472011-02-26 01:02:56 +00005612PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005613PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5614 Py_ssize_t size,
5615 const char *errors,
5616 int byteorder)
5617{
5618 PyObject *result;
5619 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5620 if (tmp == NULL)
5621 return NULL;
5622 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5623 Py_DECREF(tmp);
5624 return result;
5625}
5626
5627PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005628PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005629{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005630 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631}
5632
5633/* --- Unicode Escape Codec ----------------------------------------------- */
5634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5636 if all the escapes in the string make it still a valid ASCII string.
5637 Returns -1 if any escapes were found which cause the string to
5638 pop out of ASCII range. Otherwise returns the length of the
5639 required buffer to hold the string.
5640 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005641static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5643{
5644 const unsigned char *p = (const unsigned char *)s;
5645 const unsigned char *end = p + size;
5646 Py_ssize_t length = 0;
5647
5648 if (size < 0)
5649 return -1;
5650
5651 for (; p < end; ++p) {
5652 if (*p > 127) {
5653 /* Non-ASCII */
5654 return -1;
5655 }
5656 else if (*p != '\\') {
5657 /* Normal character */
5658 ++length;
5659 }
5660 else {
5661 /* Backslash-escape, check next char */
5662 ++p;
5663 /* Escape sequence reaches till end of string or
5664 non-ASCII follow-up. */
5665 if (p >= end || *p > 127)
5666 return -1;
5667 switch (*p) {
5668 case '\n':
5669 /* backslash + \n result in zero characters */
5670 break;
5671 case '\\': case '\'': case '\"':
5672 case 'b': case 'f': case 't':
5673 case 'n': case 'r': case 'v': case 'a':
5674 ++length;
5675 break;
5676 case '0': case '1': case '2': case '3':
5677 case '4': case '5': case '6': case '7':
5678 case 'x': case 'u': case 'U': case 'N':
5679 /* these do not guarantee ASCII characters */
5680 return -1;
5681 default:
5682 /* count the backslash + the other character */
5683 length += 2;
5684 }
5685 }
5686 }
5687 return length;
5688}
5689
Fredrik Lundh06d12682001-01-24 07:59:11 +00005690static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005691
Alexander Belopolsky40018472011-02-26 01:02:56 +00005692PyObject *
5693PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005694 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005695 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005697 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005698 Py_ssize_t startinpos;
5699 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005700 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005702 char* message;
5703 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005704 PyObject *errorHandler = NULL;
5705 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005707
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005709 if (len == 0)
5710 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711
5712 /* After length_of_escaped_ascii_string() there are two alternatives,
5713 either the string is pure ASCII with named escapes like \n, etc.
5714 and we determined it's exact size (common case)
5715 or it contains \x, \u, ... escape sequences. then we create a
5716 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005717 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005718 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005719 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005720 }
5721 else {
5722 /* Escaped strings will always be longer than the resulting
5723 Unicode string, so we start with size here and then reduce the
5724 length after conversion to the true value.
5725 (but if the error callback returns a long replacement string
5726 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005727 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005728 }
5729
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005731 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005733
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 while (s < end) {
5735 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005736 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738
5739 /* Non-escape characters are interpreted as Unicode ordinals */
5740 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005741 x = (unsigned char)*s;
5742 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005743 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005744 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745 continue;
5746 }
5747
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005748 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 /* \ - Escapes */
5750 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005751 c = *s++;
5752 if (s > end)
5753 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005755 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005758#define WRITECHAR(ch) \
5759 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005760 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005761 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005762 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005763
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005765 case '\\': WRITECHAR('\\'); break;
5766 case '\'': WRITECHAR('\''); break;
5767 case '\"': WRITECHAR('\"'); break;
5768 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005770 case 'f': WRITECHAR('\014'); break;
5771 case 't': WRITECHAR('\t'); break;
5772 case 'n': WRITECHAR('\n'); break;
5773 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005774 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005775 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005776 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005777 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 case '0': case '1': case '2': case '3':
5781 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005782 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005783 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005784 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005785 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005786 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005787 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005788 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789 break;
5790
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 /* hex escapes */
5792 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005793 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005794 digits = 2;
5795 message = "truncated \\xXX escape";
5796 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005797
Benjamin Peterson29060642009-01-31 22:14:21 +00005798 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005800 digits = 4;
5801 message = "truncated \\uXXXX escape";
5802 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005803
Benjamin Peterson29060642009-01-31 22:14:21 +00005804 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005805 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005806 digits = 8;
5807 message = "truncated \\UXXXXXXXX escape";
5808 hexescape:
5809 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005810 if (end - s < digits) {
5811 /* count only hex digits */
5812 for (; s < end; ++s) {
5813 c = (unsigned char)*s;
5814 if (!Py_ISXDIGIT(c))
5815 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005816 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005817 goto error;
5818 }
5819 for (; digits--; ++s) {
5820 c = (unsigned char)*s;
5821 if (!Py_ISXDIGIT(c))
5822 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005823 chr = (chr<<4) & ~0xF;
5824 if (c >= '0' && c <= '9')
5825 chr += c - '0';
5826 else if (c >= 'a' && c <= 'f')
5827 chr += 10 + c - 'a';
5828 else
5829 chr += 10 + c - 'A';
5830 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005831 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 /* _decoding_error will have already written into the
5833 target buffer. */
5834 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005835 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005836 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005837 message = "illegal Unicode character";
5838 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005839 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005840 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005841 break;
5842
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005844 case 'N':
5845 message = "malformed \\N character escape";
5846 if (ucnhash_CAPI == NULL) {
5847 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005848 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5849 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005850 if (ucnhash_CAPI == NULL)
5851 goto ucnhashError;
5852 }
5853 if (*s == '{') {
5854 const char *start = s+1;
5855 /* look for the closing brace */
5856 while (*s != '}' && s < end)
5857 s++;
5858 if (s > start && s < end && *s == '}') {
5859 /* found a name. look it up in the unicode database */
5860 message = "unknown Unicode character name";
5861 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005862 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005863 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005864 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005865 goto store;
5866 }
5867 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005868 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005869
5870 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005871 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005872 message = "\\ at end of string";
5873 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005874 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005875 }
5876 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005877 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005878 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005879 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005880 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005882 continue;
5883
5884 error:
5885 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005886 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005887 errors, &errorHandler,
5888 "unicodeescape", message,
5889 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005890 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005891 goto onError;
5892 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005894#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005895
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005896 Py_XDECREF(errorHandler);
5897 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005898 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005899
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005901 PyErr_SetString(
5902 PyExc_UnicodeError,
5903 "\\N escapes not supported (can't load unicodedata module)"
5904 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005905 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005906 Py_XDECREF(errorHandler);
5907 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005908 return NULL;
5909
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005911 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005912 Py_XDECREF(errorHandler);
5913 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 return NULL;
5915}
5916
5917/* Return a Unicode-Escape string version of the Unicode object.
5918
5919 If quotes is true, the string is enclosed in u"" or u'' quotes as
5920 appropriate.
5921
5922*/
5923
Alexander Belopolsky40018472011-02-26 01:02:56 +00005924PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005925PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005927 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005928 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005930 int kind;
5931 void *data;
5932 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Ezio Melottie7f90372012-10-05 03:33:31 +03005934 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005935 escape.
5936
Ezio Melottie7f90372012-10-05 03:33:31 +03005937 For UCS1 strings it's '\xxx', 4 bytes per source character.
5938 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5939 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005940 */
5941
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005942 if (!PyUnicode_Check(unicode)) {
5943 PyErr_BadArgument();
5944 return NULL;
5945 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005946 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947 return NULL;
5948 len = PyUnicode_GET_LENGTH(unicode);
5949 kind = PyUnicode_KIND(unicode);
5950 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005951 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005952 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5953 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5954 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5955 }
5956
5957 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005958 return PyBytes_FromStringAndSize(NULL, 0);
5959
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005960 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005965 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005966 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 if (repr == NULL)
5968 return NULL;
5969
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005970 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005972 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005973 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005974
Walter Dörwald79e913e2007-05-12 11:08:06 +00005975 /* Escape backslashes */
5976 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 *p++ = '\\';
5978 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005979 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005980 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005981
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005982 /* Map 21-bit characters to '\U00xxxxxx' */
5983 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005984 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005985 *p++ = '\\';
5986 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005987 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5989 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5993 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5994 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005996 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005997
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005999 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 *p++ = '\\';
6001 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006002 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6003 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6004 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6005 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006007
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006008 /* Map special whitespace to '\t', \n', '\r' */
6009 else if (ch == '\t') {
6010 *p++ = '\\';
6011 *p++ = 't';
6012 }
6013 else if (ch == '\n') {
6014 *p++ = '\\';
6015 *p++ = 'n';
6016 }
6017 else if (ch == '\r') {
6018 *p++ = '\\';
6019 *p++ = 'r';
6020 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006021
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006022 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006023 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006025 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006026 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6027 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006028 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006029
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030 /* Copy everything else as-is */
6031 else
6032 *p++ = (char) ch;
6033 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006035 assert(p - PyBytes_AS_STRING(repr) > 0);
6036 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6037 return NULL;
6038 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039}
6040
Alexander Belopolsky40018472011-02-26 01:02:56 +00006041PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006042PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6043 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006045 PyObject *result;
6046 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6047 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006049 result = PyUnicode_AsUnicodeEscapeString(tmp);
6050 Py_DECREF(tmp);
6051 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052}
6053
6054/* --- Raw Unicode Escape Codec ------------------------------------------- */
6055
Alexander Belopolsky40018472011-02-26 01:02:56 +00006056PyObject *
6057PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006058 Py_ssize_t size,
6059 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006061 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006062 Py_ssize_t startinpos;
6063 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006064 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065 const char *end;
6066 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006067 PyObject *errorHandler = NULL;
6068 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006069
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006070 if (size == 0)
6071 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006072
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 /* Escaped strings will always be longer than the resulting
6074 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006075 length after conversion to the true value. (But decoding error
6076 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006077 _PyUnicodeWriter_Init(&writer);
6078 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006079
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080 end = s + size;
6081 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 unsigned char c;
6083 Py_UCS4 x;
6084 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006085 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 /* Non-escape characters are interpreted as Unicode ordinals */
6088 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006089 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006090 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006091 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006093 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 startinpos = s-starts;
6095
6096 /* \u-escapes are only interpreted iff the number of leading
6097 backslashes if odd */
6098 bs = s;
6099 for (;s < end;) {
6100 if (*s != '\\')
6101 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006102 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006103 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006104 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 }
6106 if (((s - bs) & 1) == 0 ||
6107 s >= end ||
6108 (*s != 'u' && *s != 'U')) {
6109 continue;
6110 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006111 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 count = *s=='u' ? 4 : 8;
6113 s++;
6114
6115 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 for (x = 0, i = 0; i < count; ++i, ++s) {
6117 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006118 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006120 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006121 errors, &errorHandler,
6122 "rawunicodeescape", "truncated \\uXXXX",
6123 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006124 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006125 goto onError;
6126 goto nextByte;
6127 }
6128 x = (x<<4) & ~0xF;
6129 if (c >= '0' && c <= '9')
6130 x += c - '0';
6131 else if (c >= 'a' && c <= 'f')
6132 x += 10 + c - 'a';
6133 else
6134 x += 10 + c - 'A';
6135 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006136 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006137 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006138 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006139 }
6140 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006141 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006142 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006143 errors, &errorHandler,
6144 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006146 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006148 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 nextByte:
6150 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006152 Py_XDECREF(errorHandler);
6153 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006154 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006155
Benjamin Peterson29060642009-01-31 22:14:21 +00006156 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006157 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006158 Py_XDECREF(errorHandler);
6159 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 return NULL;
6161}
6162
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006163
Alexander Belopolsky40018472011-02-26 01:02:56 +00006164PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006166{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006167 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006168 char *p;
6169 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006170 Py_ssize_t expandsize, pos;
6171 int kind;
6172 void *data;
6173 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 if (!PyUnicode_Check(unicode)) {
6176 PyErr_BadArgument();
6177 return NULL;
6178 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006179 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006180 return NULL;
6181 kind = PyUnicode_KIND(unicode);
6182 data = PyUnicode_DATA(unicode);
6183 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006184 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6185 bytes, and 1 byte characters 4. */
6186 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006187
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006188 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006189 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006190
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 if (repr == NULL)
6193 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006194 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006195 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006197 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006198 for (pos = 0; pos < len; pos++) {
6199 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006200 /* Map 32-bit characters to '\Uxxxxxxxx' */
6201 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006202 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006203 *p++ = '\\';
6204 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006205 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6207 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6208 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6209 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6211 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6212 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006213 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006214 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006215 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 *p++ = '\\';
6217 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006218 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6219 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6220 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6221 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 /* Copy everything else as-is */
6224 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 *p++ = (char) ch;
6226 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006227
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006228 assert(p > q);
6229 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006230 return NULL;
6231 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232}
6233
Alexander Belopolsky40018472011-02-26 01:02:56 +00006234PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006235PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6236 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006238 PyObject *result;
6239 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6240 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006241 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006242 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6243 Py_DECREF(tmp);
6244 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006245}
6246
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006247/* --- Unicode Internal Codec ------------------------------------------- */
6248
Alexander Belopolsky40018472011-02-26 01:02:56 +00006249PyObject *
6250_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006251 Py_ssize_t size,
6252 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006253{
6254 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006255 Py_ssize_t startinpos;
6256 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006257 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006258 const char *end;
6259 const char *reason;
6260 PyObject *errorHandler = NULL;
6261 PyObject *exc = NULL;
6262
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006263 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006264 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006265 1))
6266 return NULL;
6267
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006268 if (size == 0)
6269 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006270
Victor Stinner8f674cc2013-04-17 23:02:17 +02006271 _PyUnicodeWriter_Init(&writer);
6272 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6273 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006275 }
6276 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006277
Victor Stinner8f674cc2013-04-17 23:02:17 +02006278 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006280 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006281 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006282 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006283 endinpos = end-starts;
6284 reason = "truncated input";
6285 goto error;
6286 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006287 /* We copy the raw representation one byte at a time because the
6288 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006289 ((char *) &uch)[0] = s[0];
6290 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006291#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006292 ((char *) &uch)[2] = s[2];
6293 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006294#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006295 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006296#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006297 /* We have to sanity check the raw data, otherwise doom looms for
6298 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006299 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006300 endinpos = s - starts + Py_UNICODE_SIZE;
6301 reason = "illegal code point (> 0x10FFFF)";
6302 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006303 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006304#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006305 s += Py_UNICODE_SIZE;
6306#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006307 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006308 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006309 Py_UNICODE uch2;
6310 ((char *) &uch2)[0] = s[0];
6311 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006312 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006313 {
Victor Stinner551ac952011-11-29 22:58:13 +01006314 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006315 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006316 }
6317 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006318#endif
6319
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006320 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006321 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006322 continue;
6323
6324 error:
6325 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006326 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006327 errors, &errorHandler,
6328 "unicode_internal", reason,
6329 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006330 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006331 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006332 }
6333
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006334 Py_XDECREF(errorHandler);
6335 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006336 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006337
Benjamin Peterson29060642009-01-31 22:14:21 +00006338 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006339 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006340 Py_XDECREF(errorHandler);
6341 Py_XDECREF(exc);
6342 return NULL;
6343}
6344
Guido van Rossumd57fd912000-03-10 22:53:23 +00006345/* --- Latin-1 Codec ------------------------------------------------------ */
6346
Alexander Belopolsky40018472011-02-26 01:02:56 +00006347PyObject *
6348PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006349 Py_ssize_t size,
6350 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006352 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006353 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354}
6355
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357static void
6358make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006359 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006360 PyObject *unicode,
6361 Py_ssize_t startpos, Py_ssize_t endpos,
6362 const char *reason)
6363{
6364 if (*exceptionObject == NULL) {
6365 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006367 encoding, unicode, startpos, endpos, reason);
6368 }
6369 else {
6370 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6371 goto onError;
6372 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6373 goto onError;
6374 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6375 goto onError;
6376 return;
6377 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006378 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006379 }
6380}
6381
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006383static void
6384raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006385 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006386 PyObject *unicode,
6387 Py_ssize_t startpos, Py_ssize_t endpos,
6388 const char *reason)
6389{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006390 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006391 encoding, unicode, startpos, endpos, reason);
6392 if (*exceptionObject != NULL)
6393 PyCodec_StrictErrors(*exceptionObject);
6394}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006395
6396/* error handling callback helper:
6397 build arguments, call the callback and check the arguments,
6398 put the result into newpos and return the replacement string, which
6399 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006400static PyObject *
6401unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006402 PyObject **errorHandler,
6403 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006405 Py_ssize_t startpos, Py_ssize_t endpos,
6406 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006407{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006408 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006409 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006410 PyObject *restuple;
6411 PyObject *resunicode;
6412
6413 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006415 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 }
6418
Benjamin Petersonbac79492012-01-14 13:34:47 -05006419 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 return NULL;
6421 len = PyUnicode_GET_LENGTH(unicode);
6422
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006423 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006424 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427
6428 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006433 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006434 Py_DECREF(restuple);
6435 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006437 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006438 &resunicode, newpos)) {
6439 Py_DECREF(restuple);
6440 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006441 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006442 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6443 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6444 Py_DECREF(restuple);
6445 return NULL;
6446 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006448 *newpos = len + *newpos;
6449 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006450 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006451 Py_DECREF(restuple);
6452 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006453 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454 Py_INCREF(resunicode);
6455 Py_DECREF(restuple);
6456 return resunicode;
6457}
6458
Alexander Belopolsky40018472011-02-26 01:02:56 +00006459static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006460unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006461 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006462 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006464 /* input state */
6465 Py_ssize_t pos=0, size;
6466 int kind;
6467 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006468 /* output object */
6469 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470 /* pointer into the output */
6471 char *str;
6472 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006473 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006474 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6475 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476 PyObject *errorHandler = NULL;
6477 PyObject *exc = NULL;
6478 /* the following variable is used for caching string comparisons
6479 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6480 int known_errorHandler = -1;
6481
Benjamin Petersonbac79492012-01-14 13:34:47 -05006482 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 return NULL;
6484 size = PyUnicode_GET_LENGTH(unicode);
6485 kind = PyUnicode_KIND(unicode);
6486 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006487 /* allocate enough for a simple encoding without
6488 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006489 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006490 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006491 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006492 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006493 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006494 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006495 ressize = size;
6496
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006497 while (pos < size) {
6498 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006499
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 /* can we encode this? */
6501 if (c<limit) {
6502 /* no overflow check, because we know that the space is enough */
6503 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006505 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 Py_ssize_t requiredsize;
6508 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006509 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 Py_ssize_t collstart = pos;
6512 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006514 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 ++collend;
6516 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6517 if (known_errorHandler==-1) {
6518 if ((errors==NULL) || (!strcmp(errors, "strict")))
6519 known_errorHandler = 1;
6520 else if (!strcmp(errors, "replace"))
6521 known_errorHandler = 2;
6522 else if (!strcmp(errors, "ignore"))
6523 known_errorHandler = 3;
6524 else if (!strcmp(errors, "xmlcharrefreplace"))
6525 known_errorHandler = 4;
6526 else
6527 known_errorHandler = 0;
6528 }
6529 switch (known_errorHandler) {
6530 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006531 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 goto onError;
6533 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006534 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 *str++ = '?'; /* fall through */
6536 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006537 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 break;
6539 case 4: /* xmlcharrefreplace */
6540 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006541 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006543 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006545 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006547 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006549 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006550 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006551 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006553 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006555 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006556 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006557 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006558 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006559 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006560 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006561 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006562 if (requiredsize > PY_SSIZE_T_MAX - incr)
6563 goto overflow;
6564 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006566 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6567 goto overflow;
6568 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006570 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 requiredsize = 2*ressize;
6572 if (_PyBytes_Resize(&res, requiredsize))
6573 goto onError;
6574 str = PyBytes_AS_STRING(res) + respos;
6575 ressize = requiredsize;
6576 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 /* generate replacement */
6578 for (i = collstart; i < collend; ++i) {
6579 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006580 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 break;
6583 default:
6584 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006585 encoding, reason, unicode, &exc,
6586 collstart, collend, &newpos);
6587 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006588 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006590 if (PyBytes_Check(repunicode)) {
6591 /* Directly copy bytes result to output. */
6592 repsize = PyBytes_Size(repunicode);
6593 if (repsize > 1) {
6594 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006595 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006596 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6597 Py_DECREF(repunicode);
6598 goto overflow;
6599 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006600 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6601 Py_DECREF(repunicode);
6602 goto onError;
6603 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006604 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006605 ressize += repsize-1;
6606 }
6607 memcpy(str, PyBytes_AsString(repunicode), repsize);
6608 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006610 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006611 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006612 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 /* need more space? (at least enough for what we
6614 have+the replacement+the rest of the string, so
6615 we won't have to check space for encodable characters) */
6616 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006618 requiredsize = respos;
6619 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6620 goto overflow;
6621 requiredsize += repsize;
6622 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6623 goto overflow;
6624 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006625 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006626 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 requiredsize = 2*ressize;
6628 if (_PyBytes_Resize(&res, requiredsize)) {
6629 Py_DECREF(repunicode);
6630 goto onError;
6631 }
6632 str = PyBytes_AS_STRING(res) + respos;
6633 ressize = requiredsize;
6634 }
6635 /* check if there is anything unencodable in the replacement
6636 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 for (i = 0; repsize-->0; ++i, ++str) {
6638 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006639 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006640 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006641 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 Py_DECREF(repunicode);
6643 goto onError;
6644 }
6645 *str = (char)c;
6646 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006648 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006649 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006650 }
6651 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006652 /* Resize if we allocated to much */
6653 size = str - PyBytes_AS_STRING(res);
6654 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006655 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006656 if (_PyBytes_Resize(&res, size) < 0)
6657 goto onError;
6658 }
6659
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006660 Py_XDECREF(errorHandler);
6661 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006662 return res;
6663
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006664 overflow:
6665 PyErr_SetString(PyExc_OverflowError,
6666 "encoded result is too long for a Python string");
6667
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006668 onError:
6669 Py_XDECREF(res);
6670 Py_XDECREF(errorHandler);
6671 Py_XDECREF(exc);
6672 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673}
6674
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006676PyObject *
6677PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006678 Py_ssize_t size,
6679 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006680{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681 PyObject *result;
6682 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6683 if (unicode == NULL)
6684 return NULL;
6685 result = unicode_encode_ucs1(unicode, errors, 256);
6686 Py_DECREF(unicode);
6687 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006688}
6689
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006691_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006692{
6693 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006694 PyErr_BadArgument();
6695 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006696 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006697 if (PyUnicode_READY(unicode) == -1)
6698 return NULL;
6699 /* Fast path: if it is a one-byte string, construct
6700 bytes object directly. */
6701 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6702 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6703 PyUnicode_GET_LENGTH(unicode));
6704 /* Non-Latin-1 characters present. Defer to above function to
6705 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006707}
6708
6709PyObject*
6710PyUnicode_AsLatin1String(PyObject *unicode)
6711{
6712 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006713}
6714
6715/* --- 7-bit ASCII Codec -------------------------------------------------- */
6716
Alexander Belopolsky40018472011-02-26 01:02:56 +00006717PyObject *
6718PyUnicode_DecodeASCII(const char *s,
6719 Py_ssize_t size,
6720 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006722 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006723 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006724 int kind;
6725 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006726 Py_ssize_t startinpos;
6727 Py_ssize_t endinpos;
6728 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006729 const char *e;
6730 PyObject *errorHandler = NULL;
6731 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006732
Guido van Rossumd57fd912000-03-10 22:53:23 +00006733 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006734 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006735
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006737 if (size == 1 && (unsigned char)s[0] < 128)
6738 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006739
Victor Stinner8f674cc2013-04-17 23:02:17 +02006740 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006741 writer.min_length = size;
6742 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006743 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006744
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006745 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006746 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006747 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006748 writer.pos = outpos;
6749 if (writer.pos == size)
6750 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006751
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006752 s += writer.pos;
6753 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006755 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006756 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006757 PyUnicode_WRITE(kind, data, writer.pos, c);
6758 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006759 ++s;
6760 }
6761 else {
6762 startinpos = s-starts;
6763 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006764 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 errors, &errorHandler,
6766 "ascii", "ordinal not in range(128)",
6767 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006768 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006769 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006770 kind = writer.kind;
6771 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006773 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006774 Py_XDECREF(errorHandler);
6775 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006776 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006777
Benjamin Peterson29060642009-01-31 22:14:21 +00006778 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006779 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006780 Py_XDECREF(errorHandler);
6781 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006782 return NULL;
6783}
6784
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006785/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006786PyObject *
6787PyUnicode_EncodeASCII(const Py_UNICODE *p,
6788 Py_ssize_t size,
6789 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006790{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006791 PyObject *result;
6792 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6793 if (unicode == NULL)
6794 return NULL;
6795 result = unicode_encode_ucs1(unicode, errors, 128);
6796 Py_DECREF(unicode);
6797 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006798}
6799
Alexander Belopolsky40018472011-02-26 01:02:56 +00006800PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006801_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006802{
6803 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 PyErr_BadArgument();
6805 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006807 if (PyUnicode_READY(unicode) == -1)
6808 return NULL;
6809 /* Fast path: if it is an ASCII-only string, construct bytes object
6810 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006811 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006812 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6813 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006814 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006815}
6816
6817PyObject *
6818PyUnicode_AsASCIIString(PyObject *unicode)
6819{
6820 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006821}
6822
Victor Stinner99b95382011-07-04 14:23:54 +02006823#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006824
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006825/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006826
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006827#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006828#define NEED_RETRY
6829#endif
6830
Victor Stinner3a50e702011-10-18 21:21:00 +02006831#ifndef WC_ERR_INVALID_CHARS
6832# define WC_ERR_INVALID_CHARS 0x0080
6833#endif
6834
6835static char*
6836code_page_name(UINT code_page, PyObject **obj)
6837{
6838 *obj = NULL;
6839 if (code_page == CP_ACP)
6840 return "mbcs";
6841 if (code_page == CP_UTF7)
6842 return "CP_UTF7";
6843 if (code_page == CP_UTF8)
6844 return "CP_UTF8";
6845
6846 *obj = PyBytes_FromFormat("cp%u", code_page);
6847 if (*obj == NULL)
6848 return NULL;
6849 return PyBytes_AS_STRING(*obj);
6850}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006851
Alexander Belopolsky40018472011-02-26 01:02:56 +00006852static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006853is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006854{
6855 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006856 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006857
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 if (!IsDBCSLeadByteEx(code_page, *curr))
6859 return 0;
6860
6861 prev = CharPrevExA(code_page, s, curr, 0);
6862 if (prev == curr)
6863 return 1;
6864 /* FIXME: This code is limited to "true" double-byte encodings,
6865 as it assumes an incomplete character consists of a single
6866 byte. */
6867 if (curr - prev == 2)
6868 return 1;
6869 if (!IsDBCSLeadByteEx(code_page, *prev))
6870 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871 return 0;
6872}
6873
Victor Stinner3a50e702011-10-18 21:21:00 +02006874static DWORD
6875decode_code_page_flags(UINT code_page)
6876{
6877 if (code_page == CP_UTF7) {
6878 /* The CP_UTF7 decoder only supports flags=0 */
6879 return 0;
6880 }
6881 else
6882 return MB_ERR_INVALID_CHARS;
6883}
6884
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006885/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 * Decode a byte string from a Windows code page into unicode object in strict
6887 * mode.
6888 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006889 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6890 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006891 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006892static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006893decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006894 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006895 const char *in,
6896 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006897{
Victor Stinner3a50e702011-10-18 21:21:00 +02006898 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006899 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006900 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006901
6902 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006903 assert(insize > 0);
6904 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6905 if (outsize <= 0)
6906 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006907
6908 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006909 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006910 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006911 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006912 if (*v == NULL)
6913 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006914 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006915 }
6916 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006917 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006918 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006919 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006920 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006921 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006922 }
6923
6924 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006925 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6926 if (outsize <= 0)
6927 goto error;
6928 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006929
Victor Stinner3a50e702011-10-18 21:21:00 +02006930error:
6931 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6932 return -2;
6933 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006934 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006935}
6936
Victor Stinner3a50e702011-10-18 21:21:00 +02006937/*
6938 * Decode a byte string from a code page into unicode object with an error
6939 * handler.
6940 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006941 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006942 * UnicodeDecodeError exception and returns -1 on error.
6943 */
6944static int
6945decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006946 PyObject **v,
6947 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006948 const char *errors)
6949{
6950 const char *startin = in;
6951 const char *endin = in + size;
6952 const DWORD flags = decode_code_page_flags(code_page);
6953 /* Ideally, we should get reason from FormatMessage. This is the Windows
6954 2000 English version of the message. */
6955 const char *reason = "No mapping for the Unicode character exists "
6956 "in the target code page.";
6957 /* each step cannot decode more than 1 character, but a character can be
6958 represented as a surrogate pair */
6959 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006960 int insize;
6961 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006962 PyObject *errorHandler = NULL;
6963 PyObject *exc = NULL;
6964 PyObject *encoding_obj = NULL;
6965 char *encoding;
6966 DWORD err;
6967 int ret = -1;
6968
6969 assert(size > 0);
6970
6971 encoding = code_page_name(code_page, &encoding_obj);
6972 if (encoding == NULL)
6973 return -1;
6974
6975 if (errors == NULL || strcmp(errors, "strict") == 0) {
6976 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6977 UnicodeDecodeError. */
6978 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6979 if (exc != NULL) {
6980 PyCodec_StrictErrors(exc);
6981 Py_CLEAR(exc);
6982 }
6983 goto error;
6984 }
6985
6986 if (*v == NULL) {
6987 /* Create unicode object */
6988 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6989 PyErr_NoMemory();
6990 goto error;
6991 }
Victor Stinnerab595942011-12-17 04:59:06 +01006992 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006993 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 if (*v == NULL)
6995 goto error;
6996 startout = PyUnicode_AS_UNICODE(*v);
6997 }
6998 else {
6999 /* Extend unicode object */
7000 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7001 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7002 PyErr_NoMemory();
7003 goto error;
7004 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007005 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007006 goto error;
7007 startout = PyUnicode_AS_UNICODE(*v) + n;
7008 }
7009
7010 /* Decode the byte string character per character */
7011 out = startout;
7012 while (in < endin)
7013 {
7014 /* Decode a character */
7015 insize = 1;
7016 do
7017 {
7018 outsize = MultiByteToWideChar(code_page, flags,
7019 in, insize,
7020 buffer, Py_ARRAY_LENGTH(buffer));
7021 if (outsize > 0)
7022 break;
7023 err = GetLastError();
7024 if (err != ERROR_NO_UNICODE_TRANSLATION
7025 && err != ERROR_INSUFFICIENT_BUFFER)
7026 {
7027 PyErr_SetFromWindowsErr(0);
7028 goto error;
7029 }
7030 insize++;
7031 }
7032 /* 4=maximum length of a UTF-8 sequence */
7033 while (insize <= 4 && (in + insize) <= endin);
7034
7035 if (outsize <= 0) {
7036 Py_ssize_t startinpos, endinpos, outpos;
7037
7038 startinpos = in - startin;
7039 endinpos = startinpos + 1;
7040 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007041 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 errors, &errorHandler,
7043 encoding, reason,
7044 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007045 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 {
7047 goto error;
7048 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007049 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 }
7051 else {
7052 in += insize;
7053 memcpy(out, buffer, outsize * sizeof(wchar_t));
7054 out += outsize;
7055 }
7056 }
7057
7058 /* write a NUL character at the end */
7059 *out = 0;
7060
7061 /* Extend unicode object */
7062 outsize = out - startout;
7063 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007064 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007067
7068error:
7069 Py_XDECREF(encoding_obj);
7070 Py_XDECREF(errorHandler);
7071 Py_XDECREF(exc);
7072 return ret;
7073}
7074
Victor Stinner3a50e702011-10-18 21:21:00 +02007075static PyObject *
7076decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007077 const char *s, Py_ssize_t size,
7078 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079{
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 PyObject *v = NULL;
7081 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007082
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 if (code_page < 0) {
7084 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7085 return NULL;
7086 }
7087
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007089 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
Victor Stinner76a31a62011-11-04 00:05:13 +01007091 do
7092 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007093#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007094 if (size > INT_MAX) {
7095 chunk_size = INT_MAX;
7096 final = 0;
7097 done = 0;
7098 }
7099 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007100#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007101 {
7102 chunk_size = (int)size;
7103 final = (consumed == NULL);
7104 done = 1;
7105 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106
Victor Stinner76a31a62011-11-04 00:05:13 +01007107 /* Skip trailing lead-byte unless 'final' is set */
7108 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7109 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110
Victor Stinner76a31a62011-11-04 00:05:13 +01007111 if (chunk_size == 0 && done) {
7112 if (v != NULL)
7113 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007114 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007115 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007116
Victor Stinner76a31a62011-11-04 00:05:13 +01007117
7118 converted = decode_code_page_strict(code_page, &v,
7119 s, chunk_size);
7120 if (converted == -2)
7121 converted = decode_code_page_errors(code_page, &v,
7122 s, chunk_size,
7123 errors);
7124 assert(converted != 0);
7125
7126 if (converted < 0) {
7127 Py_XDECREF(v);
7128 return NULL;
7129 }
7130
7131 if (consumed)
7132 *consumed += converted;
7133
7134 s += converted;
7135 size -= converted;
7136 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007137
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007138 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139}
7140
Alexander Belopolsky40018472011-02-26 01:02:56 +00007141PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007142PyUnicode_DecodeCodePageStateful(int code_page,
7143 const char *s,
7144 Py_ssize_t size,
7145 const char *errors,
7146 Py_ssize_t *consumed)
7147{
7148 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7149}
7150
7151PyObject *
7152PyUnicode_DecodeMBCSStateful(const char *s,
7153 Py_ssize_t size,
7154 const char *errors,
7155 Py_ssize_t *consumed)
7156{
7157 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7158}
7159
7160PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007161PyUnicode_DecodeMBCS(const char *s,
7162 Py_ssize_t size,
7163 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007164{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007165 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7166}
7167
Victor Stinner3a50e702011-10-18 21:21:00 +02007168static DWORD
7169encode_code_page_flags(UINT code_page, const char *errors)
7170{
7171 if (code_page == CP_UTF8) {
7172 if (winver.dwMajorVersion >= 6)
7173 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7174 and later */
7175 return WC_ERR_INVALID_CHARS;
7176 else
7177 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7178 return 0;
7179 }
7180 else if (code_page == CP_UTF7) {
7181 /* CP_UTF7 only supports flags=0 */
7182 return 0;
7183 }
7184 else {
7185 if (errors != NULL && strcmp(errors, "replace") == 0)
7186 return 0;
7187 else
7188 return WC_NO_BEST_FIT_CHARS;
7189 }
7190}
7191
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007192/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 * Encode a Unicode string to a Windows code page into a byte string in strict
7194 * mode.
7195 *
7196 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007197 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007198 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007199static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007200encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007201 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007202 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007203{
Victor Stinner554f3f02010-06-16 23:33:54 +00007204 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 BOOL *pusedDefaultChar = &usedDefaultChar;
7206 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007207 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007208 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007209 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 const DWORD flags = encode_code_page_flags(code_page, NULL);
7211 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 /* Create a substring so that we can get the UTF-16 representation
7213 of just the slice under consideration. */
7214 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007215
Martin v. Löwis3d325192011-11-04 18:23:06 +01007216 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007217
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007219 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007221 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007222
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 substring = PyUnicode_Substring(unicode, offset, offset+len);
7224 if (substring == NULL)
7225 return -1;
7226 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7227 if (p == NULL) {
7228 Py_DECREF(substring);
7229 return -1;
7230 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007231 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007232
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007233 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007235 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 NULL, 0,
7237 NULL, pusedDefaultChar);
7238 if (outsize <= 0)
7239 goto error;
7240 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007241 if (pusedDefaultChar && *pusedDefaultChar) {
7242 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007244 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007245
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007247 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007249 if (*outbytes == NULL) {
7250 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007251 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007252 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007254 }
7255 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007256 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007257 const Py_ssize_t n = PyBytes_Size(*outbytes);
7258 if (outsize > PY_SSIZE_T_MAX - n) {
7259 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007260 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007261 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007262 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007263 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7264 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007266 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268 }
7269
7270 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007272 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 out, outsize,
7274 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007275 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007276 if (outsize <= 0)
7277 goto error;
7278 if (pusedDefaultChar && *pusedDefaultChar)
7279 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007280 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007281
Victor Stinner3a50e702011-10-18 21:21:00 +02007282error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007283 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7285 return -2;
7286 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007287 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007288}
7289
Victor Stinner3a50e702011-10-18 21:21:00 +02007290/*
7291 * Encode a Unicode string to a Windows code page into a byte string using a
7292 * error handler.
7293 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007294 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007295 * -1 on other error.
7296 */
7297static int
7298encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007299 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007300 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007301{
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007303 Py_ssize_t pos = unicode_offset;
7304 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 /* Ideally, we should get reason from FormatMessage. This is the Windows
7306 2000 English version of the message. */
7307 const char *reason = "invalid character";
7308 /* 4=maximum length of a UTF-8 sequence */
7309 char buffer[4];
7310 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7311 Py_ssize_t outsize;
7312 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007313 PyObject *errorHandler = NULL;
7314 PyObject *exc = NULL;
7315 PyObject *encoding_obj = NULL;
7316 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007317 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 PyObject *rep;
7319 int ret = -1;
7320
7321 assert(insize > 0);
7322
7323 encoding = code_page_name(code_page, &encoding_obj);
7324 if (encoding == NULL)
7325 return -1;
7326
7327 if (errors == NULL || strcmp(errors, "strict") == 0) {
7328 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7329 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007330 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007331 if (exc != NULL) {
7332 PyCodec_StrictErrors(exc);
7333 Py_DECREF(exc);
7334 }
7335 Py_XDECREF(encoding_obj);
7336 return -1;
7337 }
7338
7339 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7340 pusedDefaultChar = &usedDefaultChar;
7341 else
7342 pusedDefaultChar = NULL;
7343
7344 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7345 PyErr_NoMemory();
7346 goto error;
7347 }
7348 outsize = insize * Py_ARRAY_LENGTH(buffer);
7349
7350 if (*outbytes == NULL) {
7351 /* Create string object */
7352 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7353 if (*outbytes == NULL)
7354 goto error;
7355 out = PyBytes_AS_STRING(*outbytes);
7356 }
7357 else {
7358 /* Extend string object */
7359 Py_ssize_t n = PyBytes_Size(*outbytes);
7360 if (n > PY_SSIZE_T_MAX - outsize) {
7361 PyErr_NoMemory();
7362 goto error;
7363 }
7364 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7365 goto error;
7366 out = PyBytes_AS_STRING(*outbytes) + n;
7367 }
7368
7369 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007370 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007372 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7373 wchar_t chars[2];
7374 int charsize;
7375 if (ch < 0x10000) {
7376 chars[0] = (wchar_t)ch;
7377 charsize = 1;
7378 }
7379 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007380 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7381 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007382 charsize = 2;
7383 }
7384
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007386 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 buffer, Py_ARRAY_LENGTH(buffer),
7388 NULL, pusedDefaultChar);
7389 if (outsize > 0) {
7390 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7391 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007392 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 memcpy(out, buffer, outsize);
7394 out += outsize;
7395 continue;
7396 }
7397 }
7398 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7399 PyErr_SetFromWindowsErr(0);
7400 goto error;
7401 }
7402
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 rep = unicode_encode_call_errorhandler(
7404 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007405 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007406 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 if (rep == NULL)
7408 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007409 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007410
7411 if (PyBytes_Check(rep)) {
7412 outsize = PyBytes_GET_SIZE(rep);
7413 if (outsize != 1) {
7414 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7415 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7416 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7417 Py_DECREF(rep);
7418 goto error;
7419 }
7420 out = PyBytes_AS_STRING(*outbytes) + offset;
7421 }
7422 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7423 out += outsize;
7424 }
7425 else {
7426 Py_ssize_t i;
7427 enum PyUnicode_Kind kind;
7428 void *data;
7429
Benjamin Petersonbac79492012-01-14 13:34:47 -05007430 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 Py_DECREF(rep);
7432 goto error;
7433 }
7434
7435 outsize = PyUnicode_GET_LENGTH(rep);
7436 if (outsize != 1) {
7437 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7438 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7439 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7440 Py_DECREF(rep);
7441 goto error;
7442 }
7443 out = PyBytes_AS_STRING(*outbytes) + offset;
7444 }
7445 kind = PyUnicode_KIND(rep);
7446 data = PyUnicode_DATA(rep);
7447 for (i=0; i < outsize; i++) {
7448 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7449 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007450 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007451 encoding, unicode,
7452 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 "unable to encode error handler result to ASCII");
7454 Py_DECREF(rep);
7455 goto error;
7456 }
7457 *out = (unsigned char)ch;
7458 out++;
7459 }
7460 }
7461 Py_DECREF(rep);
7462 }
7463 /* write a NUL byte */
7464 *out = 0;
7465 outsize = out - PyBytes_AS_STRING(*outbytes);
7466 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7467 if (_PyBytes_Resize(outbytes, outsize) < 0)
7468 goto error;
7469 ret = 0;
7470
7471error:
7472 Py_XDECREF(encoding_obj);
7473 Py_XDECREF(errorHandler);
7474 Py_XDECREF(exc);
7475 return ret;
7476}
7477
Victor Stinner3a50e702011-10-18 21:21:00 +02007478static PyObject *
7479encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007480 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 const char *errors)
7482{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007485 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007486 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007487
Benjamin Petersonbac79492012-01-14 13:34:47 -05007488 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007489 return NULL;
7490 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007491
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 if (code_page < 0) {
7493 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7494 return NULL;
7495 }
7496
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007498 return PyBytes_FromStringAndSize(NULL, 0);
7499
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 offset = 0;
7501 do
7502 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007504 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007505 chunks. */
7506 if (len > INT_MAX/2) {
7507 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007508 done = 0;
7509 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007510 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007511#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007512 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007513 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007514 done = 1;
7515 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007516
Victor Stinner76a31a62011-11-04 00:05:13 +01007517 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007518 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007519 errors);
7520 if (ret == -2)
7521 ret = encode_code_page_errors(code_page, &outbytes,
7522 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007523 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007524 if (ret < 0) {
7525 Py_XDECREF(outbytes);
7526 return NULL;
7527 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007528
Victor Stinner7581cef2011-11-03 22:32:33 +01007529 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007530 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007531 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007532
Victor Stinner3a50e702011-10-18 21:21:00 +02007533 return outbytes;
7534}
7535
7536PyObject *
7537PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7538 Py_ssize_t size,
7539 const char *errors)
7540{
Victor Stinner7581cef2011-11-03 22:32:33 +01007541 PyObject *unicode, *res;
7542 unicode = PyUnicode_FromUnicode(p, size);
7543 if (unicode == NULL)
7544 return NULL;
7545 res = encode_code_page(CP_ACP, unicode, errors);
7546 Py_DECREF(unicode);
7547 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007548}
7549
7550PyObject *
7551PyUnicode_EncodeCodePage(int code_page,
7552 PyObject *unicode,
7553 const char *errors)
7554{
Victor Stinner7581cef2011-11-03 22:32:33 +01007555 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007556}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007557
Alexander Belopolsky40018472011-02-26 01:02:56 +00007558PyObject *
7559PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007560{
7561 if (!PyUnicode_Check(unicode)) {
7562 PyErr_BadArgument();
7563 return NULL;
7564 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007565 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007566}
7567
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007568#undef NEED_RETRY
7569
Victor Stinner99b95382011-07-04 14:23:54 +02007570#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007571
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572/* --- Character Mapping Codec -------------------------------------------- */
7573
Victor Stinnerfb161b12013-04-18 01:44:27 +02007574static int
7575charmap_decode_string(const char *s,
7576 Py_ssize_t size,
7577 PyObject *mapping,
7578 const char *errors,
7579 _PyUnicodeWriter *writer)
7580{
7581 const char *starts = s;
7582 const char *e;
7583 Py_ssize_t startinpos, endinpos;
7584 PyObject *errorHandler = NULL, *exc = NULL;
7585 Py_ssize_t maplen;
7586 enum PyUnicode_Kind mapkind;
7587 void *mapdata;
7588 Py_UCS4 x;
7589 unsigned char ch;
7590
7591 if (PyUnicode_READY(mapping) == -1)
7592 return -1;
7593
7594 maplen = PyUnicode_GET_LENGTH(mapping);
7595 mapdata = PyUnicode_DATA(mapping);
7596 mapkind = PyUnicode_KIND(mapping);
7597
7598 e = s + size;
7599
7600 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7601 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7602 * is disabled in encoding aliases, latin1 is preferred because
7603 * its implementation is faster. */
7604 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7605 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7606 Py_UCS4 maxchar = writer->maxchar;
7607
7608 assert (writer->kind == PyUnicode_1BYTE_KIND);
7609 while (s < e) {
7610 ch = *s;
7611 x = mapdata_ucs1[ch];
7612 if (x > maxchar) {
7613 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7614 goto onError;
7615 maxchar = writer->maxchar;
7616 outdata = (Py_UCS1 *)writer->data;
7617 }
7618 outdata[writer->pos] = x;
7619 writer->pos++;
7620 ++s;
7621 }
7622 return 0;
7623 }
7624
7625 while (s < e) {
7626 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7627 enum PyUnicode_Kind outkind = writer->kind;
7628 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7629 if (outkind == PyUnicode_1BYTE_KIND) {
7630 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7631 Py_UCS4 maxchar = writer->maxchar;
7632 while (s < e) {
7633 ch = *s;
7634 x = mapdata_ucs2[ch];
7635 if (x > maxchar)
7636 goto Error;
7637 outdata[writer->pos] = x;
7638 writer->pos++;
7639 ++s;
7640 }
7641 break;
7642 }
7643 else if (outkind == PyUnicode_2BYTE_KIND) {
7644 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7645 while (s < e) {
7646 ch = *s;
7647 x = mapdata_ucs2[ch];
7648 if (x == 0xFFFE)
7649 goto Error;
7650 outdata[writer->pos] = x;
7651 writer->pos++;
7652 ++s;
7653 }
7654 break;
7655 }
7656 }
7657 ch = *s;
7658
7659 if (ch < maplen)
7660 x = PyUnicode_READ(mapkind, mapdata, ch);
7661 else
7662 x = 0xfffe; /* invalid value */
7663Error:
7664 if (x == 0xfffe)
7665 {
7666 /* undefined mapping */
7667 startinpos = s-starts;
7668 endinpos = startinpos+1;
7669 if (unicode_decode_call_errorhandler_writer(
7670 errors, &errorHandler,
7671 "charmap", "character maps to <undefined>",
7672 &starts, &e, &startinpos, &endinpos, &exc, &s,
7673 writer)) {
7674 goto onError;
7675 }
7676 continue;
7677 }
7678
7679 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7680 goto onError;
7681 ++s;
7682 }
7683 Py_XDECREF(errorHandler);
7684 Py_XDECREF(exc);
7685 return 0;
7686
7687onError:
7688 Py_XDECREF(errorHandler);
7689 Py_XDECREF(exc);
7690 return -1;
7691}
7692
7693static int
7694charmap_decode_mapping(const char *s,
7695 Py_ssize_t size,
7696 PyObject *mapping,
7697 const char *errors,
7698 _PyUnicodeWriter *writer)
7699{
7700 const char *starts = s;
7701 const char *e;
7702 Py_ssize_t startinpos, endinpos;
7703 PyObject *errorHandler = NULL, *exc = NULL;
7704 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007705 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007706
7707 e = s + size;
7708
7709 while (s < e) {
7710 ch = *s;
7711
7712 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7713 key = PyLong_FromLong((long)ch);
7714 if (key == NULL)
7715 goto onError;
7716
7717 item = PyObject_GetItem(mapping, key);
7718 Py_DECREF(key);
7719 if (item == NULL) {
7720 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7721 /* No mapping found means: mapping is undefined. */
7722 PyErr_Clear();
7723 goto Undefined;
7724 } else
7725 goto onError;
7726 }
7727
7728 /* Apply mapping */
7729 if (item == Py_None)
7730 goto Undefined;
7731 if (PyLong_Check(item)) {
7732 long value = PyLong_AS_LONG(item);
7733 if (value == 0xFFFE)
7734 goto Undefined;
7735 if (value < 0 || value > MAX_UNICODE) {
7736 PyErr_Format(PyExc_TypeError,
7737 "character mapping must be in range(0x%lx)",
7738 (unsigned long)MAX_UNICODE + 1);
7739 goto onError;
7740 }
7741
7742 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7743 goto onError;
7744 }
7745 else if (PyUnicode_Check(item)) {
7746 if (PyUnicode_READY(item) == -1)
7747 goto onError;
7748 if (PyUnicode_GET_LENGTH(item) == 1) {
7749 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7750 if (value == 0xFFFE)
7751 goto Undefined;
7752 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7753 goto onError;
7754 }
7755 else {
7756 writer->overallocate = 1;
7757 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7758 goto onError;
7759 }
7760 }
7761 else {
7762 /* wrong return value */
7763 PyErr_SetString(PyExc_TypeError,
7764 "character mapping must return integer, None or str");
7765 goto onError;
7766 }
7767 Py_CLEAR(item);
7768 ++s;
7769 continue;
7770
7771Undefined:
7772 /* undefined mapping */
7773 Py_CLEAR(item);
7774 startinpos = s-starts;
7775 endinpos = startinpos+1;
7776 if (unicode_decode_call_errorhandler_writer(
7777 errors, &errorHandler,
7778 "charmap", "character maps to <undefined>",
7779 &starts, &e, &startinpos, &endinpos, &exc, &s,
7780 writer)) {
7781 goto onError;
7782 }
7783 }
7784 Py_XDECREF(errorHandler);
7785 Py_XDECREF(exc);
7786 return 0;
7787
7788onError:
7789 Py_XDECREF(item);
7790 Py_XDECREF(errorHandler);
7791 Py_XDECREF(exc);
7792 return -1;
7793}
7794
Alexander Belopolsky40018472011-02-26 01:02:56 +00007795PyObject *
7796PyUnicode_DecodeCharmap(const char *s,
7797 Py_ssize_t size,
7798 PyObject *mapping,
7799 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007800{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007801 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007802
Guido van Rossumd57fd912000-03-10 22:53:23 +00007803 /* Default to Latin-1 */
7804 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007806
Guido van Rossumd57fd912000-03-10 22:53:23 +00007807 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007808 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007809 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007810 writer.min_length = size;
7811 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007812 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007813
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007814 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007815 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7816 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007817 }
7818 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007819 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7820 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007822 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007823
Benjamin Peterson29060642009-01-31 22:14:21 +00007824 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007825 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826 return NULL;
7827}
7828
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829/* Charmap encoding: the lookup table */
7830
Alexander Belopolsky40018472011-02-26 01:02:56 +00007831struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 PyObject_HEAD
7833 unsigned char level1[32];
7834 int count2, count3;
7835 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007836};
7837
7838static PyObject*
7839encoding_map_size(PyObject *obj, PyObject* args)
7840{
7841 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007842 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007843 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844}
7845
7846static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007847 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007848 PyDoc_STR("Return the size (in bytes) of this object") },
7849 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007850};
7851
7852static void
7853encoding_map_dealloc(PyObject* o)
7854{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007855 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007856}
7857
7858static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007859 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007860 "EncodingMap", /*tp_name*/
7861 sizeof(struct encoding_map), /*tp_basicsize*/
7862 0, /*tp_itemsize*/
7863 /* methods */
7864 encoding_map_dealloc, /*tp_dealloc*/
7865 0, /*tp_print*/
7866 0, /*tp_getattr*/
7867 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007868 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 0, /*tp_repr*/
7870 0, /*tp_as_number*/
7871 0, /*tp_as_sequence*/
7872 0, /*tp_as_mapping*/
7873 0, /*tp_hash*/
7874 0, /*tp_call*/
7875 0, /*tp_str*/
7876 0, /*tp_getattro*/
7877 0, /*tp_setattro*/
7878 0, /*tp_as_buffer*/
7879 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7880 0, /*tp_doc*/
7881 0, /*tp_traverse*/
7882 0, /*tp_clear*/
7883 0, /*tp_richcompare*/
7884 0, /*tp_weaklistoffset*/
7885 0, /*tp_iter*/
7886 0, /*tp_iternext*/
7887 encoding_map_methods, /*tp_methods*/
7888 0, /*tp_members*/
7889 0, /*tp_getset*/
7890 0, /*tp_base*/
7891 0, /*tp_dict*/
7892 0, /*tp_descr_get*/
7893 0, /*tp_descr_set*/
7894 0, /*tp_dictoffset*/
7895 0, /*tp_init*/
7896 0, /*tp_alloc*/
7897 0, /*tp_new*/
7898 0, /*tp_free*/
7899 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007900};
7901
7902PyObject*
7903PyUnicode_BuildEncodingMap(PyObject* string)
7904{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 PyObject *result;
7906 struct encoding_map *mresult;
7907 int i;
7908 int need_dict = 0;
7909 unsigned char level1[32];
7910 unsigned char level2[512];
7911 unsigned char *mlevel1, *mlevel2, *mlevel3;
7912 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007913 int kind;
7914 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007915 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007916 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007918 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919 PyErr_BadArgument();
7920 return NULL;
7921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007922 kind = PyUnicode_KIND(string);
7923 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007924 length = PyUnicode_GET_LENGTH(string);
7925 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926 memset(level1, 0xFF, sizeof level1);
7927 memset(level2, 0xFF, sizeof level2);
7928
7929 /* If there isn't a one-to-one mapping of NULL to \0,
7930 or if there are non-BMP characters, we need to use
7931 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007932 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007934 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007936 ch = PyUnicode_READ(kind, data, i);
7937 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938 need_dict = 1;
7939 break;
7940 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007941 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942 /* unmapped character */
7943 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007944 l1 = ch >> 11;
7945 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007946 if (level1[l1] == 0xFF)
7947 level1[l1] = count2++;
7948 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007949 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 }
7951
7952 if (count2 >= 0xFF || count3 >= 0xFF)
7953 need_dict = 1;
7954
7955 if (need_dict) {
7956 PyObject *result = PyDict_New();
7957 PyObject *key, *value;
7958 if (!result)
7959 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007960 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007961 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007962 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007963 if (!key || !value)
7964 goto failed1;
7965 if (PyDict_SetItem(result, key, value) == -1)
7966 goto failed1;
7967 Py_DECREF(key);
7968 Py_DECREF(value);
7969 }
7970 return result;
7971 failed1:
7972 Py_XDECREF(key);
7973 Py_XDECREF(value);
7974 Py_DECREF(result);
7975 return NULL;
7976 }
7977
7978 /* Create a three-level trie */
7979 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7980 16*count2 + 128*count3 - 1);
7981 if (!result)
7982 return PyErr_NoMemory();
7983 PyObject_Init(result, &EncodingMapType);
7984 mresult = (struct encoding_map*)result;
7985 mresult->count2 = count2;
7986 mresult->count3 = count3;
7987 mlevel1 = mresult->level1;
7988 mlevel2 = mresult->level23;
7989 mlevel3 = mresult->level23 + 16*count2;
7990 memcpy(mlevel1, level1, 32);
7991 memset(mlevel2, 0xFF, 16*count2);
7992 memset(mlevel3, 0, 128*count3);
7993 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007994 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007995 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007996 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7997 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007998 /* unmapped character */
7999 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008000 o1 = ch>>11;
8001 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002 i2 = 16*mlevel1[o1] + o2;
8003 if (mlevel2[i2] == 0xFF)
8004 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008005 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006 i3 = 128*mlevel2[i2] + o3;
8007 mlevel3[i3] = i;
8008 }
8009 return result;
8010}
8011
8012static int
Victor Stinner22168992011-11-20 17:09:18 +01008013encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008014{
8015 struct encoding_map *map = (struct encoding_map*)mapping;
8016 int l1 = c>>11;
8017 int l2 = (c>>7) & 0xF;
8018 int l3 = c & 0x7F;
8019 int i;
8020
Victor Stinner22168992011-11-20 17:09:18 +01008021 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008023 if (c == 0)
8024 return 0;
8025 /* level 1*/
8026 i = map->level1[l1];
8027 if (i == 0xFF) {
8028 return -1;
8029 }
8030 /* level 2*/
8031 i = map->level23[16*i+l2];
8032 if (i == 0xFF) {
8033 return -1;
8034 }
8035 /* level 3 */
8036 i = map->level23[16*map->count2 + 128*i + l3];
8037 if (i == 0) {
8038 return -1;
8039 }
8040 return i;
8041}
8042
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043/* Lookup the character ch in the mapping. If the character
8044 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008045 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008046static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008047charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008048{
Christian Heimes217cfd12007-12-02 14:31:20 +00008049 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008050 PyObject *x;
8051
8052 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008053 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008054 x = PyObject_GetItem(mapping, w);
8055 Py_DECREF(w);
8056 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8058 /* No mapping found means: mapping is undefined. */
8059 PyErr_Clear();
8060 x = Py_None;
8061 Py_INCREF(x);
8062 return x;
8063 } else
8064 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008065 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008066 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008068 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 long value = PyLong_AS_LONG(x);
8070 if (value < 0 || value > 255) {
8071 PyErr_SetString(PyExc_TypeError,
8072 "character mapping must be in range(256)");
8073 Py_DECREF(x);
8074 return NULL;
8075 }
8076 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008077 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008078 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008079 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008080 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 /* wrong return value */
8082 PyErr_Format(PyExc_TypeError,
8083 "character mapping must return integer, bytes or None, not %.400s",
8084 x->ob_type->tp_name);
8085 Py_DECREF(x);
8086 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008087 }
8088}
8089
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008091charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008093 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8094 /* exponentially overallocate to minimize reallocations */
8095 if (requiredsize < 2*outsize)
8096 requiredsize = 2*outsize;
8097 if (_PyBytes_Resize(outobj, requiredsize))
8098 return -1;
8099 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100}
8101
Benjamin Peterson14339b62009-01-31 16:36:08 +00008102typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008103 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008104} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008106 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 space is available. Return a new reference to the object that
8108 was put in the output buffer, or Py_None, if the mapping was undefined
8109 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008110 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008111static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008112charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008113 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008114{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115 PyObject *rep;
8116 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008117 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008118
Christian Heimes90aa7642007-12-19 02:45:37 +00008119 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008120 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 if (res == -1)
8123 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 if (outsize<requiredsize)
8125 if (charmapencode_resize(outobj, outpos, requiredsize))
8126 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008127 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 outstart[(*outpos)++] = (char)res;
8129 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 }
8131
8132 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008134 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008135 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 Py_DECREF(rep);
8137 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008138 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008139 if (PyLong_Check(rep)) {
8140 Py_ssize_t requiredsize = *outpos+1;
8141 if (outsize<requiredsize)
8142 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8143 Py_DECREF(rep);
8144 return enc_EXCEPTION;
8145 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008146 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008148 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 else {
8150 const char *repchars = PyBytes_AS_STRING(rep);
8151 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8152 Py_ssize_t requiredsize = *outpos+repsize;
8153 if (outsize<requiredsize)
8154 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8155 Py_DECREF(rep);
8156 return enc_EXCEPTION;
8157 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008158 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 memcpy(outstart + *outpos, repchars, repsize);
8160 *outpos += repsize;
8161 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008162 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008163 Py_DECREF(rep);
8164 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008165}
8166
8167/* handle an error in PyUnicode_EncodeCharmap
8168 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008169static int
8170charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008171 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008172 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008173 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008174 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008175{
8176 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008177 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008178 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008179 enum PyUnicode_Kind kind;
8180 void *data;
8181 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008182 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008183 Py_ssize_t collstartpos = *inpos;
8184 Py_ssize_t collendpos = *inpos+1;
8185 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008186 char *encoding = "charmap";
8187 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008189 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008190 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008191
Benjamin Petersonbac79492012-01-14 13:34:47 -05008192 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008193 return -1;
8194 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195 /* find all unencodable characters */
8196 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008197 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008198 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008199 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008200 val = encoding_map_lookup(ch, mapping);
8201 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 break;
8203 ++collendpos;
8204 continue;
8205 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008207 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8208 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 if (rep==NULL)
8210 return -1;
8211 else if (rep!=Py_None) {
8212 Py_DECREF(rep);
8213 break;
8214 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008215 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217 }
8218 /* cache callback name lookup
8219 * (if not done yet, i.e. it's the first error) */
8220 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 if ((errors==NULL) || (!strcmp(errors, "strict")))
8222 *known_errorHandler = 1;
8223 else if (!strcmp(errors, "replace"))
8224 *known_errorHandler = 2;
8225 else if (!strcmp(errors, "ignore"))
8226 *known_errorHandler = 3;
8227 else if (!strcmp(errors, "xmlcharrefreplace"))
8228 *known_errorHandler = 4;
8229 else
8230 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 }
8232 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008233 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008234 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008235 return -1;
8236 case 2: /* replace */
8237 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 x = charmapencode_output('?', mapping, res, respos);
8239 if (x==enc_EXCEPTION) {
8240 return -1;
8241 }
8242 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008243 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 return -1;
8245 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008246 }
8247 /* fall through */
8248 case 3: /* ignore */
8249 *inpos = collendpos;
8250 break;
8251 case 4: /* xmlcharrefreplace */
8252 /* generate replacement (temporarily (mis)uses p) */
8253 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008254 char buffer[2+29+1+1];
8255 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008256 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 for (cp = buffer; *cp; ++cp) {
8258 x = charmapencode_output(*cp, mapping, res, respos);
8259 if (x==enc_EXCEPTION)
8260 return -1;
8261 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008262 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 return -1;
8264 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008265 }
8266 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008267 *inpos = collendpos;
8268 break;
8269 default:
8270 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008271 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008273 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008275 if (PyBytes_Check(repunicode)) {
8276 /* Directly copy bytes result to output. */
8277 Py_ssize_t outsize = PyBytes_Size(*res);
8278 Py_ssize_t requiredsize;
8279 repsize = PyBytes_Size(repunicode);
8280 requiredsize = *respos + repsize;
8281 if (requiredsize > outsize)
8282 /* Make room for all additional bytes. */
8283 if (charmapencode_resize(res, respos, requiredsize)) {
8284 Py_DECREF(repunicode);
8285 return -1;
8286 }
8287 memcpy(PyBytes_AsString(*res) + *respos,
8288 PyBytes_AsString(repunicode), repsize);
8289 *respos += repsize;
8290 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008291 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008292 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008293 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008294 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008295 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008296 Py_DECREF(repunicode);
8297 return -1;
8298 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008299 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008300 data = PyUnicode_DATA(repunicode);
8301 kind = PyUnicode_KIND(repunicode);
8302 for (index = 0; index < repsize; index++) {
8303 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8304 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008306 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 return -1;
8308 }
8309 else if (x==enc_FAILED) {
8310 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008311 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008312 return -1;
8313 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 }
8315 *inpos = newpos;
8316 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008317 }
8318 return 0;
8319}
8320
Alexander Belopolsky40018472011-02-26 01:02:56 +00008321PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322_PyUnicode_EncodeCharmap(PyObject *unicode,
8323 PyObject *mapping,
8324 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008325{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326 /* output object */
8327 PyObject *res = NULL;
8328 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008329 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008330 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008332 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 PyObject *errorHandler = NULL;
8334 PyObject *exc = NULL;
8335 /* the following variable is used for caching string comparisons
8336 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8337 * 3=ignore, 4=xmlcharrefreplace */
8338 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008339 void *data;
8340 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008341
Benjamin Petersonbac79492012-01-14 13:34:47 -05008342 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008343 return NULL;
8344 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008345 data = PyUnicode_DATA(unicode);
8346 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008347
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348 /* Default to Latin-1 */
8349 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008350 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008351
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 /* allocate enough for a simple encoding without
8353 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008354 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 if (res == NULL)
8356 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008357 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008359
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008361 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008363 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 if (x==enc_EXCEPTION) /* error */
8365 goto onError;
8366 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 &exc,
8369 &known_errorHandler, &errorHandler, errors,
8370 &res, &respos)) {
8371 goto onError;
8372 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008373 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 else
8375 /* done with this character => adjust input position */
8376 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008380 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008381 if (_PyBytes_Resize(&res, respos) < 0)
8382 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008383
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 Py_XDECREF(exc);
8385 Py_XDECREF(errorHandler);
8386 return res;
8387
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 Py_XDECREF(res);
8390 Py_XDECREF(exc);
8391 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008392 return NULL;
8393}
8394
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008395/* Deprecated */
8396PyObject *
8397PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8398 Py_ssize_t size,
8399 PyObject *mapping,
8400 const char *errors)
8401{
8402 PyObject *result;
8403 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8404 if (unicode == NULL)
8405 return NULL;
8406 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8407 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008408 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008409}
8410
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411PyObject *
8412PyUnicode_AsCharmapString(PyObject *unicode,
8413 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008414{
8415 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 PyErr_BadArgument();
8417 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008418 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008419 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008420}
8421
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008423static void
8424make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008425 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008426 Py_ssize_t startpos, Py_ssize_t endpos,
8427 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008428{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 *exceptionObject = _PyUnicodeTranslateError_Create(
8431 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008432 }
8433 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8435 goto onError;
8436 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8437 goto onError;
8438 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8439 goto onError;
8440 return;
8441 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008442 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008443 }
8444}
8445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446/* error handling callback helper:
8447 build arguments, call the callback and check the arguments,
8448 put the result into newpos and return the replacement string, which
8449 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008450static PyObject *
8451unicode_translate_call_errorhandler(const char *errors,
8452 PyObject **errorHandler,
8453 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008455 Py_ssize_t startpos, Py_ssize_t endpos,
8456 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008458 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008460 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461 PyObject *restuple;
8462 PyObject *resunicode;
8463
8464 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 }
8469
8470 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008471 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474
8475 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008480 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 Py_DECREF(restuple);
8482 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 }
8484 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 &resunicode, &i_newpos)) {
8486 Py_DECREF(restuple);
8487 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008489 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008491 else
8492 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008493 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008494 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 Py_DECREF(restuple);
8496 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008497 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 Py_INCREF(resunicode);
8499 Py_DECREF(restuple);
8500 return resunicode;
8501}
8502
8503/* Lookup the character ch in the mapping and put the result in result,
8504 which must be decrefed by the caller.
8505 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008506static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508{
Christian Heimes217cfd12007-12-02 14:31:20 +00008509 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 PyObject *x;
8511
8512 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 x = PyObject_GetItem(mapping, w);
8515 Py_DECREF(w);
8516 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8518 /* No mapping found means: use 1:1 mapping. */
8519 PyErr_Clear();
8520 *result = NULL;
8521 return 0;
8522 } else
8523 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524 }
8525 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 *result = x;
8527 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008529 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 long value = PyLong_AS_LONG(x);
8531 long max = PyUnicode_GetMax();
8532 if (value < 0 || value > max) {
8533 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008534 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 Py_DECREF(x);
8536 return -1;
8537 }
8538 *result = x;
8539 return 0;
8540 }
8541 else if (PyUnicode_Check(x)) {
8542 *result = x;
8543 return 0;
8544 }
8545 else {
8546 /* wrong return value */
8547 PyErr_SetString(PyExc_TypeError,
8548 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008549 Py_DECREF(x);
8550 return -1;
8551 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552}
8553/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 if not reallocate and adjust various state variables.
8555 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008556static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008560 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008561 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008562 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 /* exponentially overallocate to minimize reallocations */
8564 if (requiredsize < 2 * oldsize)
8565 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008566 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8567 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008569 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008571 }
8572 return 0;
8573}
8574/* lookup the character, put the result in the output string and adjust
8575 various state variables. Return a new reference to the object that
8576 was put in the output buffer in *result, or Py_None, if the mapping was
8577 undefined (in which case no character was written).
8578 The called must decref result.
8579 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008580static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8582 PyObject *mapping, Py_UCS4 **output,
8583 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008584 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008585{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008586 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8587 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592 }
8593 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008595 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 }
8599 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 Py_ssize_t repsize;
8601 if (PyUnicode_READY(*res) == -1)
8602 return -1;
8603 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 if (repsize==1) {
8605 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008607 }
8608 else if (repsize!=0) {
8609 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 Py_ssize_t requiredsize = *opos +
8611 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 Py_ssize_t i;
8614 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 for(i = 0; i < repsize; i++)
8617 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619 }
8620 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622 return 0;
8623}
8624
Alexander Belopolsky40018472011-02-26 01:02:56 +00008625PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626_PyUnicode_TranslateCharmap(PyObject *input,
8627 PyObject *mapping,
8628 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 /* input object */
8631 char *idata;
8632 Py_ssize_t size, i;
8633 int kind;
8634 /* output buffer */
8635 Py_UCS4 *output = NULL;
8636 Py_ssize_t osize;
8637 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 char *reason = "character maps to <undefined>";
8641 PyObject *errorHandler = NULL;
8642 PyObject *exc = NULL;
8643 /* the following variable is used for caching string comparisons
8644 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8645 * 3=ignore, 4=xmlcharrefreplace */
8646 int known_errorHandler = -1;
8647
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 PyErr_BadArgument();
8650 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008651 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653 if (PyUnicode_READY(input) == -1)
8654 return NULL;
8655 idata = (char*)PyUnicode_DATA(input);
8656 kind = PyUnicode_KIND(input);
8657 size = PyUnicode_GET_LENGTH(input);
8658 i = 0;
8659
8660 if (size == 0) {
8661 Py_INCREF(input);
8662 return input;
8663 }
8664
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 /* allocate enough for a simple 1:1 translation without
8666 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 osize = size;
8668 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8669 opos = 0;
8670 if (output == NULL) {
8671 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 /* try to encode it */
8677 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 if (charmaptranslate_output(input, i, mapping,
8679 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 Py_XDECREF(x);
8681 goto onError;
8682 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008683 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 else { /* untranslatable character */
8687 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8688 Py_ssize_t repsize;
8689 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008690 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 Py_ssize_t collstart = i;
8693 Py_ssize_t collend = i+1;
8694 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008695
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 while (collend < size) {
8698 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008699 goto onError;
8700 Py_XDECREF(x);
8701 if (x!=Py_None)
8702 break;
8703 ++collend;
8704 }
8705 /* cache callback name lookup
8706 * (if not done yet, i.e. it's the first error) */
8707 if (known_errorHandler==-1) {
8708 if ((errors==NULL) || (!strcmp(errors, "strict")))
8709 known_errorHandler = 1;
8710 else if (!strcmp(errors, "replace"))
8711 known_errorHandler = 2;
8712 else if (!strcmp(errors, "ignore"))
8713 known_errorHandler = 3;
8714 else if (!strcmp(errors, "xmlcharrefreplace"))
8715 known_errorHandler = 4;
8716 else
8717 known_errorHandler = 0;
8718 }
8719 switch (known_errorHandler) {
8720 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008721 make_translate_exception(&exc,
8722 input, collstart, collend, reason);
8723 if (exc != NULL)
8724 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008725 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 case 2: /* replace */
8727 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 for (coll = collstart; coll<collend; coll++)
8729 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 /* fall through */
8731 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 break;
8734 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 /* generate replacement (temporarily (mis)uses i) */
8736 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 char buffer[2+29+1+1];
8738 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8740 if (charmaptranslate_makespace(&output, &osize,
8741 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008742 goto onError;
8743 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 break;
8748 default:
8749 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 reason, input, &exc,
8751 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008752 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008754 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008755 Py_DECREF(repunicode);
8756 goto onError;
8757 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 repsize = PyUnicode_GET_LENGTH(repunicode);
8760 if (charmaptranslate_makespace(&output, &osize,
8761 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 Py_DECREF(repunicode);
8763 goto onError;
8764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 for (uni2 = 0; repsize-->0; ++uni2)
8766 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8767 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008769 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008770 }
8771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8773 if (!res)
8774 goto onError;
8775 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 Py_XDECREF(exc);
8777 Py_XDECREF(errorHandler);
8778 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008782 Py_XDECREF(exc);
8783 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 return NULL;
8785}
8786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787/* Deprecated. Use PyUnicode_Translate instead. */
8788PyObject *
8789PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8790 Py_ssize_t size,
8791 PyObject *mapping,
8792 const char *errors)
8793{
Christian Heimes5f520f42012-09-11 14:03:25 +02008794 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8796 if (!unicode)
8797 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008798 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8799 Py_DECREF(unicode);
8800 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801}
8802
Alexander Belopolsky40018472011-02-26 01:02:56 +00008803PyObject *
8804PyUnicode_Translate(PyObject *str,
8805 PyObject *mapping,
8806 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008807{
8808 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008809
Guido van Rossumd57fd912000-03-10 22:53:23 +00008810 str = PyUnicode_FromObject(str);
8811 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008812 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008813 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008814 Py_DECREF(str);
8815 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008816}
Tim Petersced69f82003-09-16 20:30:58 +00008817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008819fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008820{
8821 /* No need to call PyUnicode_READY(self) because this function is only
8822 called as a callback from fixup() which does it already. */
8823 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8824 const int kind = PyUnicode_KIND(self);
8825 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008826 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008827 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 Py_ssize_t i;
8829
8830 for (i = 0; i < len; ++i) {
8831 ch = PyUnicode_READ(kind, data, i);
8832 fixed = 0;
8833 if (ch > 127) {
8834 if (Py_UNICODE_ISSPACE(ch))
8835 fixed = ' ';
8836 else {
8837 const int decimal = Py_UNICODE_TODECIMAL(ch);
8838 if (decimal >= 0)
8839 fixed = '0' + decimal;
8840 }
8841 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008842 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008843 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844 PyUnicode_WRITE(kind, data, i, fixed);
8845 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008846 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008847 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 }
8850
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008851 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008852}
8853
8854PyObject *
8855_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8856{
8857 if (!PyUnicode_Check(unicode)) {
8858 PyErr_BadInternalCall();
8859 return NULL;
8860 }
8861 if (PyUnicode_READY(unicode) == -1)
8862 return NULL;
8863 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8864 /* If the string is already ASCII, just return the same string */
8865 Py_INCREF(unicode);
8866 return unicode;
8867 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008868 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869}
8870
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008871PyObject *
8872PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8873 Py_ssize_t length)
8874{
Victor Stinnerf0124502011-11-21 23:12:56 +01008875 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008876 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008877 Py_UCS4 maxchar;
8878 enum PyUnicode_Kind kind;
8879 void *data;
8880
Victor Stinner99d7ad02012-02-22 13:37:39 +01008881 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008882 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008883 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008884 if (ch > 127) {
8885 int decimal = Py_UNICODE_TODECIMAL(ch);
8886 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008887 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008888 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008889 }
8890 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008891
8892 /* Copy to a new string */
8893 decimal = PyUnicode_New(length, maxchar);
8894 if (decimal == NULL)
8895 return decimal;
8896 kind = PyUnicode_KIND(decimal);
8897 data = PyUnicode_DATA(decimal);
8898 /* Iterate over code points */
8899 for (i = 0; i < length; i++) {
8900 Py_UNICODE ch = s[i];
8901 if (ch > 127) {
8902 int decimal = Py_UNICODE_TODECIMAL(ch);
8903 if (decimal >= 0)
8904 ch = '0' + decimal;
8905 }
8906 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008908 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008909}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008910/* --- Decimal Encoder ---------------------------------------------------- */
8911
Alexander Belopolsky40018472011-02-26 01:02:56 +00008912int
8913PyUnicode_EncodeDecimal(Py_UNICODE *s,
8914 Py_ssize_t length,
8915 char *output,
8916 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008917{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008918 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008919 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008920 enum PyUnicode_Kind kind;
8921 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008922
8923 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 PyErr_BadArgument();
8925 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008926 }
8927
Victor Stinner42bf7752011-11-21 22:52:58 +01008928 unicode = PyUnicode_FromUnicode(s, length);
8929 if (unicode == NULL)
8930 return -1;
8931
Benjamin Petersonbac79492012-01-14 13:34:47 -05008932 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008933 Py_DECREF(unicode);
8934 return -1;
8935 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008936 kind = PyUnicode_KIND(unicode);
8937 data = PyUnicode_DATA(unicode);
8938
Victor Stinnerb84d7232011-11-22 01:50:07 +01008939 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008940 PyObject *exc;
8941 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008943 Py_ssize_t startpos;
8944
8945 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008946
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008948 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008949 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008950 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008951 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 decimal = Py_UNICODE_TODECIMAL(ch);
8953 if (decimal >= 0) {
8954 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008955 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008956 continue;
8957 }
8958 if (0 < ch && ch < 256) {
8959 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008960 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 continue;
8962 }
Victor Stinner6345be92011-11-25 20:09:01 +01008963
Victor Stinner42bf7752011-11-21 22:52:58 +01008964 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008965 exc = NULL;
8966 raise_encode_exception(&exc, "decimal", unicode,
8967 startpos, startpos+1,
8968 "invalid decimal Unicode string");
8969 Py_XDECREF(exc);
8970 Py_DECREF(unicode);
8971 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008972 }
8973 /* 0-terminate the output string */
8974 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008975 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008976 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008977}
8978
Guido van Rossumd57fd912000-03-10 22:53:23 +00008979/* --- Helpers ------------------------------------------------------------ */
8980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008982any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 Py_ssize_t start,
8984 Py_ssize_t end)
8985{
8986 int kind1, kind2, kind;
8987 void *buf1, *buf2;
8988 Py_ssize_t len1, len2, result;
8989
8990 kind1 = PyUnicode_KIND(s1);
8991 kind2 = PyUnicode_KIND(s2);
8992 kind = kind1 > kind2 ? kind1 : kind2;
8993 buf1 = PyUnicode_DATA(s1);
8994 buf2 = PyUnicode_DATA(s2);
8995 if (kind1 != kind)
8996 buf1 = _PyUnicode_AsKind(s1, kind);
8997 if (!buf1)
8998 return -2;
8999 if (kind2 != kind)
9000 buf2 = _PyUnicode_AsKind(s2, kind);
9001 if (!buf2) {
9002 if (kind1 != kind) PyMem_Free(buf1);
9003 return -2;
9004 }
9005 len1 = PyUnicode_GET_LENGTH(s1);
9006 len2 = PyUnicode_GET_LENGTH(s2);
9007
Victor Stinner794d5672011-10-10 03:21:36 +02009008 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009009 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009010 case PyUnicode_1BYTE_KIND:
9011 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9012 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9013 else
9014 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9015 break;
9016 case PyUnicode_2BYTE_KIND:
9017 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9018 break;
9019 case PyUnicode_4BYTE_KIND:
9020 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9021 break;
9022 default:
9023 assert(0); result = -2;
9024 }
9025 }
9026 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009027 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009028 case PyUnicode_1BYTE_KIND:
9029 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9030 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9031 else
9032 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9033 break;
9034 case PyUnicode_2BYTE_KIND:
9035 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9036 break;
9037 case PyUnicode_4BYTE_KIND:
9038 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9039 break;
9040 default:
9041 assert(0); result = -2;
9042 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 }
9044
9045 if (kind1 != kind)
9046 PyMem_Free(buf1);
9047 if (kind2 != kind)
9048 PyMem_Free(buf2);
9049
9050 return result;
9051}
9052
9053Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009054_PyUnicode_InsertThousandsGrouping(
9055 PyObject *unicode, Py_ssize_t index,
9056 Py_ssize_t n_buffer,
9057 void *digits, Py_ssize_t n_digits,
9058 Py_ssize_t min_width,
9059 const char *grouping, PyObject *thousands_sep,
9060 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061{
Victor Stinner41a863c2012-02-24 00:37:51 +01009062 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009063 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009064 Py_ssize_t thousands_sep_len;
9065 Py_ssize_t len;
9066
9067 if (unicode != NULL) {
9068 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009069 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009070 }
9071 else {
9072 kind = PyUnicode_1BYTE_KIND;
9073 data = NULL;
9074 }
9075 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9076 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9077 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9078 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009079 if (thousands_sep_kind < kind) {
9080 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9081 if (!thousands_sep_data)
9082 return -1;
9083 }
9084 else {
9085 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9086 if (!data)
9087 return -1;
9088 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009089 }
9090
Benjamin Petersonead6b532011-12-20 17:23:42 -06009091 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009093 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009094 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009095 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009096 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009097 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009098 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009100 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009102 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009103 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009104 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009105 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009106 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009107 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009108 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009109 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009111 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009112 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009113 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009114 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009115 break;
9116 default:
9117 assert(0);
9118 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009120 if (unicode != NULL && thousands_sep_kind != kind) {
9121 if (thousands_sep_kind < kind)
9122 PyMem_Free(thousands_sep_data);
9123 else
9124 PyMem_Free(data);
9125 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009126 if (unicode == NULL) {
9127 *maxchar = 127;
9128 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009129 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009130 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009131 }
9132 }
9133 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009134}
9135
9136
Thomas Wouters477c8d52006-05-27 19:21:47 +00009137/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009138#define ADJUST_INDICES(start, end, len) \
9139 if (end > len) \
9140 end = len; \
9141 else if (end < 0) { \
9142 end += len; \
9143 if (end < 0) \
9144 end = 0; \
9145 } \
9146 if (start < 0) { \
9147 start += len; \
9148 if (start < 0) \
9149 start = 0; \
9150 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009151
Alexander Belopolsky40018472011-02-26 01:02:56 +00009152Py_ssize_t
9153PyUnicode_Count(PyObject *str,
9154 PyObject *substr,
9155 Py_ssize_t start,
9156 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009157{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009158 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009159 PyObject* str_obj;
9160 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161 int kind1, kind2, kind;
9162 void *buf1 = NULL, *buf2 = NULL;
9163 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009164
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009165 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009166 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009168 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009169 if (!sub_obj) {
9170 Py_DECREF(str_obj);
9171 return -1;
9172 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009173 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009174 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009175 Py_DECREF(str_obj);
9176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 }
Tim Petersced69f82003-09-16 20:30:58 +00009178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 kind1 = PyUnicode_KIND(str_obj);
9180 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009181 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009183 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009184 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009185 if (kind2 > kind) {
9186 Py_DECREF(sub_obj);
9187 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009188 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009189 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009190 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 if (!buf2)
9193 goto onError;
9194 len1 = PyUnicode_GET_LENGTH(str_obj);
9195 len2 = PyUnicode_GET_LENGTH(sub_obj);
9196
9197 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009198 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009199 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009200 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9201 result = asciilib_count(
9202 ((Py_UCS1*)buf1) + start, end - start,
9203 buf2, len2, PY_SSIZE_T_MAX
9204 );
9205 else
9206 result = ucs1lib_count(
9207 ((Py_UCS1*)buf1) + start, end - start,
9208 buf2, len2, PY_SSIZE_T_MAX
9209 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 break;
9211 case PyUnicode_2BYTE_KIND:
9212 result = ucs2lib_count(
9213 ((Py_UCS2*)buf1) + start, end - start,
9214 buf2, len2, PY_SSIZE_T_MAX
9215 );
9216 break;
9217 case PyUnicode_4BYTE_KIND:
9218 result = ucs4lib_count(
9219 ((Py_UCS4*)buf1) + start, end - start,
9220 buf2, len2, PY_SSIZE_T_MAX
9221 );
9222 break;
9223 default:
9224 assert(0); result = 0;
9225 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009226
9227 Py_DECREF(sub_obj);
9228 Py_DECREF(str_obj);
9229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 if (kind2 != kind)
9231 PyMem_Free(buf2);
9232
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234 onError:
9235 Py_DECREF(sub_obj);
9236 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 if (kind2 != kind && buf2)
9238 PyMem_Free(buf2);
9239 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009240}
9241
Alexander Belopolsky40018472011-02-26 01:02:56 +00009242Py_ssize_t
9243PyUnicode_Find(PyObject *str,
9244 PyObject *sub,
9245 Py_ssize_t start,
9246 Py_ssize_t end,
9247 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009248{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009249 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009250
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009252 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009253 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009254 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009255 if (!sub) {
9256 Py_DECREF(str);
9257 return -2;
9258 }
9259 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9260 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009261 Py_DECREF(str);
9262 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263 }
Tim Petersced69f82003-09-16 20:30:58 +00009264
Victor Stinner794d5672011-10-10 03:21:36 +02009265 result = any_find_slice(direction,
9266 str, sub, start, end
9267 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009268
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009270 Py_DECREF(sub);
9271
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272 return result;
9273}
9274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275Py_ssize_t
9276PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9277 Py_ssize_t start, Py_ssize_t end,
9278 int direction)
9279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009281 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 if (PyUnicode_READY(str) == -1)
9283 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009284 if (start < 0 || end < 0) {
9285 PyErr_SetString(PyExc_IndexError, "string index out of range");
9286 return -2;
9287 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 if (end > PyUnicode_GET_LENGTH(str))
9289 end = PyUnicode_GET_LENGTH(str);
9290 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009291 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9292 kind, end-start, ch, direction);
9293 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009295 else
9296 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297}
9298
Alexander Belopolsky40018472011-02-26 01:02:56 +00009299static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009300tailmatch(PyObject *self,
9301 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009302 Py_ssize_t start,
9303 Py_ssize_t end,
9304 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009306 int kind_self;
9307 int kind_sub;
9308 void *data_self;
9309 void *data_sub;
9310 Py_ssize_t offset;
9311 Py_ssize_t i;
9312 Py_ssize_t end_sub;
9313
9314 if (PyUnicode_READY(self) == -1 ||
9315 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009316 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317
9318 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009319 return 1;
9320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9322 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009323 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009324 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 kind_self = PyUnicode_KIND(self);
9327 data_self = PyUnicode_DATA(self);
9328 kind_sub = PyUnicode_KIND(substring);
9329 data_sub = PyUnicode_DATA(substring);
9330 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9331
9332 if (direction > 0)
9333 offset = end;
9334 else
9335 offset = start;
9336
9337 if (PyUnicode_READ(kind_self, data_self, offset) ==
9338 PyUnicode_READ(kind_sub, data_sub, 0) &&
9339 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9340 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9341 /* If both are of the same kind, memcmp is sufficient */
9342 if (kind_self == kind_sub) {
9343 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009344 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 data_sub,
9346 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009347 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 }
9349 /* otherwise we have to compare each character by first accesing it */
9350 else {
9351 /* We do not need to compare 0 and len(substring)-1 because
9352 the if statement above ensured already that they are equal
9353 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 for (i = 1; i < end_sub; ++i) {
9355 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9356 PyUnicode_READ(kind_sub, data_sub, i))
9357 return 0;
9358 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009359 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009360 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009361 }
9362
9363 return 0;
9364}
9365
Alexander Belopolsky40018472011-02-26 01:02:56 +00009366Py_ssize_t
9367PyUnicode_Tailmatch(PyObject *str,
9368 PyObject *substr,
9369 Py_ssize_t start,
9370 Py_ssize_t end,
9371 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009373 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009374
Guido van Rossumd57fd912000-03-10 22:53:23 +00009375 str = PyUnicode_FromObject(str);
9376 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009377 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378 substr = PyUnicode_FromObject(substr);
9379 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009380 Py_DECREF(str);
9381 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 }
Tim Petersced69f82003-09-16 20:30:58 +00009383
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009384 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009386 Py_DECREF(str);
9387 Py_DECREF(substr);
9388 return result;
9389}
9390
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391/* Apply fixfct filter to the Unicode object self and return a
9392 reference to the modified object */
9393
Alexander Belopolsky40018472011-02-26 01:02:56 +00009394static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009395fixup(PyObject *self,
9396 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 PyObject *u;
9399 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009400 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009402 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009403 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009404 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009405 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 /* fix functions return the new maximum character in a string,
9408 if the kind of the resulting unicode object does not change,
9409 everything is fine. Otherwise we need to change the string kind
9410 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009411 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009412
9413 if (maxchar_new == 0) {
9414 /* no changes */;
9415 if (PyUnicode_CheckExact(self)) {
9416 Py_DECREF(u);
9417 Py_INCREF(self);
9418 return self;
9419 }
9420 else
9421 return u;
9422 }
9423
Victor Stinnere6abb482012-05-02 01:15:40 +02009424 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425
Victor Stinnereaab6042011-12-11 22:22:39 +01009426 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009428
9429 /* In case the maximum character changed, we need to
9430 convert the string to the new category. */
9431 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9432 if (v == NULL) {
9433 Py_DECREF(u);
9434 return NULL;
9435 }
9436 if (maxchar_new > maxchar_old) {
9437 /* If the maxchar increased so that the kind changed, not all
9438 characters are representable anymore and we need to fix the
9439 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009440 _PyUnicode_FastCopyCharacters(v, 0,
9441 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009442 maxchar_old = fixfct(v);
9443 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 }
9445 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009446 _PyUnicode_FastCopyCharacters(v, 0,
9447 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009449 Py_DECREF(u);
9450 assert(_PyUnicode_CheckConsistency(v, 1));
9451 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009452}
9453
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009454static PyObject *
9455ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009456{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009457 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9458 char *resdata, *data = PyUnicode_DATA(self);
9459 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009460
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009461 res = PyUnicode_New(len, 127);
9462 if (res == NULL)
9463 return NULL;
9464 resdata = PyUnicode_DATA(res);
9465 if (lower)
9466 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009468 _Py_bytes_upper(resdata, data, len);
9469 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470}
9471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009473handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009475 Py_ssize_t j;
9476 int final_sigma;
9477 Py_UCS4 c;
9478 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009479
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009480 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9481
9482 where ! is a negation and \p{xxx} is a character with property xxx.
9483 */
9484 for (j = i - 1; j >= 0; j--) {
9485 c = PyUnicode_READ(kind, data, j);
9486 if (!_PyUnicode_IsCaseIgnorable(c))
9487 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009489 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9490 if (final_sigma) {
9491 for (j = i + 1; j < length; j++) {
9492 c = PyUnicode_READ(kind, data, j);
9493 if (!_PyUnicode_IsCaseIgnorable(c))
9494 break;
9495 }
9496 final_sigma = j == length || !_PyUnicode_IsCased(c);
9497 }
9498 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499}
9500
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009501static int
9502lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9503 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009505 /* Obscure special case. */
9506 if (c == 0x3A3) {
9507 mapped[0] = handle_capital_sigma(kind, data, length, i);
9508 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009510 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511}
9512
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009513static Py_ssize_t
9514do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009516 Py_ssize_t i, k = 0;
9517 int n_res, j;
9518 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009519
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009520 c = PyUnicode_READ(kind, data, 0);
9521 n_res = _PyUnicode_ToUpperFull(c, mapped);
9522 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009523 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009524 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009526 for (i = 1; i < length; i++) {
9527 c = PyUnicode_READ(kind, data, i);
9528 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9529 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009530 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009531 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009532 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009533 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009534 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535}
9536
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009537static Py_ssize_t
9538do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9539 Py_ssize_t i, k = 0;
9540
9541 for (i = 0; i < length; i++) {
9542 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9543 int n_res, j;
9544 if (Py_UNICODE_ISUPPER(c)) {
9545 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9546 }
9547 else if (Py_UNICODE_ISLOWER(c)) {
9548 n_res = _PyUnicode_ToUpperFull(c, mapped);
9549 }
9550 else {
9551 n_res = 1;
9552 mapped[0] = c;
9553 }
9554 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009555 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009556 res[k++] = mapped[j];
9557 }
9558 }
9559 return k;
9560}
9561
9562static Py_ssize_t
9563do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9564 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009566 Py_ssize_t i, k = 0;
9567
9568 for (i = 0; i < length; i++) {
9569 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9570 int n_res, j;
9571 if (lower)
9572 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9573 else
9574 n_res = _PyUnicode_ToUpperFull(c, mapped);
9575 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009576 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009577 res[k++] = mapped[j];
9578 }
9579 }
9580 return k;
9581}
9582
9583static Py_ssize_t
9584do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9585{
9586 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9587}
9588
9589static Py_ssize_t
9590do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9591{
9592 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9593}
9594
Benjamin Petersone51757f2012-01-12 21:10:29 -05009595static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009596do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9597{
9598 Py_ssize_t i, k = 0;
9599
9600 for (i = 0; i < length; i++) {
9601 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9602 Py_UCS4 mapped[3];
9603 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9604 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009605 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009606 res[k++] = mapped[j];
9607 }
9608 }
9609 return k;
9610}
9611
9612static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009613do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9614{
9615 Py_ssize_t i, k = 0;
9616 int previous_is_cased;
9617
9618 previous_is_cased = 0;
9619 for (i = 0; i < length; i++) {
9620 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9621 Py_UCS4 mapped[3];
9622 int n_res, j;
9623
9624 if (previous_is_cased)
9625 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9626 else
9627 n_res = _PyUnicode_ToTitleFull(c, mapped);
9628
9629 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009630 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009631 res[k++] = mapped[j];
9632 }
9633
9634 previous_is_cased = _PyUnicode_IsCased(c);
9635 }
9636 return k;
9637}
9638
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009639static PyObject *
9640case_operation(PyObject *self,
9641 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9642{
9643 PyObject *res = NULL;
9644 Py_ssize_t length, newlength = 0;
9645 int kind, outkind;
9646 void *data, *outdata;
9647 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9648
Benjamin Petersoneea48462012-01-16 14:28:50 -05009649 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009650
9651 kind = PyUnicode_KIND(self);
9652 data = PyUnicode_DATA(self);
9653 length = PyUnicode_GET_LENGTH(self);
Antoine Pitroub6dc9b72014-10-15 23:14:53 +02009654 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009655 PyErr_SetString(PyExc_OverflowError, "string is too long");
9656 return NULL;
9657 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009658 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659 if (tmp == NULL)
9660 return PyErr_NoMemory();
9661 newlength = perform(kind, data, length, tmp, &maxchar);
9662 res = PyUnicode_New(newlength, maxchar);
9663 if (res == NULL)
9664 goto leave;
9665 tmpend = tmp + newlength;
9666 outdata = PyUnicode_DATA(res);
9667 outkind = PyUnicode_KIND(res);
9668 switch (outkind) {
9669 case PyUnicode_1BYTE_KIND:
9670 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9671 break;
9672 case PyUnicode_2BYTE_KIND:
9673 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9674 break;
9675 case PyUnicode_4BYTE_KIND:
9676 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9677 break;
9678 default:
9679 assert(0);
9680 break;
9681 }
9682 leave:
9683 PyMem_FREE(tmp);
9684 return res;
9685}
9686
Tim Peters8ce9f162004-08-27 01:49:32 +00009687PyObject *
9688PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009693 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009694 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9695 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009696 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009698 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009700 int use_memcpy;
9701 unsigned char *res_data = NULL, *sep_data = NULL;
9702 PyObject *last_obj;
9703 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009705 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009706 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009707 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009708 }
9709
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009710 /* NOTE: the following code can't call back into Python code,
9711 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009712 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009713
Tim Peters05eba1f2004-08-27 21:32:02 +00009714 seqlen = PySequence_Fast_GET_SIZE(fseq);
9715 /* If empty sequence, return u"". */
9716 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009717 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009718 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009719 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009720
Tim Peters05eba1f2004-08-27 21:32:02 +00009721 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009722 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009723 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009724 if (seqlen == 1) {
9725 if (PyUnicode_CheckExact(items[0])) {
9726 res = items[0];
9727 Py_INCREF(res);
9728 Py_DECREF(fseq);
9729 return res;
9730 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009732 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009733 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009734 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009735 /* Set up sep and seplen */
9736 if (separator == NULL) {
9737 /* fall back to a blank space separator */
9738 sep = PyUnicode_FromOrdinal(' ');
9739 if (!sep)
9740 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009741 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009742 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009743 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009744 else {
9745 if (!PyUnicode_Check(separator)) {
9746 PyErr_Format(PyExc_TypeError,
9747 "separator: expected str instance,"
9748 " %.80s found",
9749 Py_TYPE(separator)->tp_name);
9750 goto onError;
9751 }
9752 if (PyUnicode_READY(separator))
9753 goto onError;
9754 sep = separator;
9755 seplen = PyUnicode_GET_LENGTH(separator);
9756 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9757 /* inc refcount to keep this code path symmetric with the
9758 above case of a blank separator */
9759 Py_INCREF(sep);
9760 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009761 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009762 }
9763
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009764 /* There are at least two things to join, or else we have a subclass
9765 * of str in the sequence.
9766 * Do a pre-pass to figure out the total amount of space we'll
9767 * need (sz), and see whether all argument are strings.
9768 */
9769 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009770#ifdef Py_DEBUG
9771 use_memcpy = 0;
9772#else
9773 use_memcpy = 1;
9774#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009775 for (i = 0; i < seqlen; i++) {
9776 const Py_ssize_t old_sz = sz;
9777 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009778 if (!PyUnicode_Check(item)) {
9779 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009780 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009781 " %.80s found",
9782 i, Py_TYPE(item)->tp_name);
9783 goto onError;
9784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 if (PyUnicode_READY(item) == -1)
9786 goto onError;
9787 sz += PyUnicode_GET_LENGTH(item);
9788 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009789 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009790 if (i != 0)
9791 sz += seplen;
9792 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9793 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009794 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009795 goto onError;
9796 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009797 if (use_memcpy && last_obj != NULL) {
9798 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9799 use_memcpy = 0;
9800 }
9801 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009802 }
Tim Petersced69f82003-09-16 20:30:58 +00009803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009804 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009805 if (res == NULL)
9806 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009807
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009808 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009809#ifdef Py_DEBUG
9810 use_memcpy = 0;
9811#else
9812 if (use_memcpy) {
9813 res_data = PyUnicode_1BYTE_DATA(res);
9814 kind = PyUnicode_KIND(res);
9815 if (seplen != 0)
9816 sep_data = PyUnicode_1BYTE_DATA(sep);
9817 }
9818#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009819 if (use_memcpy) {
9820 for (i = 0; i < seqlen; ++i) {
9821 Py_ssize_t itemlen;
9822 item = items[i];
9823
9824 /* Copy item, and maybe the separator. */
9825 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009826 Py_MEMCPY(res_data,
9827 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009828 kind * seplen);
9829 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009830 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009831
9832 itemlen = PyUnicode_GET_LENGTH(item);
9833 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009834 Py_MEMCPY(res_data,
9835 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009836 kind * itemlen);
9837 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009838 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009839 }
9840 assert(res_data == PyUnicode_1BYTE_DATA(res)
9841 + kind * PyUnicode_GET_LENGTH(res));
9842 }
9843 else {
9844 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9845 Py_ssize_t itemlen;
9846 item = items[i];
9847
9848 /* Copy item, and maybe the separator. */
9849 if (i && seplen != 0) {
9850 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9851 res_offset += seplen;
9852 }
9853
9854 itemlen = PyUnicode_GET_LENGTH(item);
9855 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009856 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009857 res_offset += itemlen;
9858 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009859 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009860 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009861 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009862
Tim Peters05eba1f2004-08-27 21:32:02 +00009863 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009865 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009867
Benjamin Peterson29060642009-01-31 22:14:21 +00009868 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009869 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009870 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009871 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872 return NULL;
9873}
9874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009875#define FILL(kind, data, value, start, length) \
9876 do { \
9877 Py_ssize_t i_ = 0; \
9878 assert(kind != PyUnicode_WCHAR_KIND); \
9879 switch ((kind)) { \
9880 case PyUnicode_1BYTE_KIND: { \
9881 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009882 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009883 break; \
9884 } \
9885 case PyUnicode_2BYTE_KIND: { \
9886 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9887 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9888 break; \
9889 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009890 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9892 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9893 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009894 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 } \
9896 } \
9897 } while (0)
9898
Victor Stinnerd3f08822012-05-29 12:57:52 +02009899void
9900_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9901 Py_UCS4 fill_char)
9902{
9903 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9904 const void *data = PyUnicode_DATA(unicode);
9905 assert(PyUnicode_IS_READY(unicode));
9906 assert(unicode_modifiable(unicode));
9907 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9908 assert(start >= 0);
9909 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9910 FILL(kind, data, fill_char, start, length);
9911}
9912
Victor Stinner3fe55312012-01-04 00:33:50 +01009913Py_ssize_t
9914PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9915 Py_UCS4 fill_char)
9916{
9917 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009918
9919 if (!PyUnicode_Check(unicode)) {
9920 PyErr_BadInternalCall();
9921 return -1;
9922 }
9923 if (PyUnicode_READY(unicode) == -1)
9924 return -1;
9925 if (unicode_check_modifiable(unicode))
9926 return -1;
9927
Victor Stinnerd3f08822012-05-29 12:57:52 +02009928 if (start < 0) {
9929 PyErr_SetString(PyExc_IndexError, "string index out of range");
9930 return -1;
9931 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009932 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9933 PyErr_SetString(PyExc_ValueError,
9934 "fill character is bigger than "
9935 "the string maximum character");
9936 return -1;
9937 }
9938
9939 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9940 length = Py_MIN(maxlen, length);
9941 if (length <= 0)
9942 return 0;
9943
Victor Stinnerd3f08822012-05-29 12:57:52 +02009944 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009945 return length;
9946}
9947
Victor Stinner9310abb2011-10-05 00:59:23 +02009948static PyObject *
9949pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009950 Py_ssize_t left,
9951 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 PyObject *u;
9955 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009956 int kind;
9957 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
9959 if (left < 0)
9960 left = 0;
9961 if (right < 0)
9962 right = 0;
9963
Victor Stinnerc4b49542011-12-11 22:44:26 +01009964 if (left == 0 && right == 0)
9965 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9968 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009969 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9970 return NULL;
9971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009973 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009975 if (!u)
9976 return NULL;
9977
9978 kind = PyUnicode_KIND(u);
9979 data = PyUnicode_DATA(u);
9980 if (left)
9981 FILL(kind, data, fill, 0, left);
9982 if (right)
9983 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009984 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009985 assert(_PyUnicode_CheckConsistency(u, 1));
9986 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009987}
9988
Alexander Belopolsky40018472011-02-26 01:02:56 +00009989PyObject *
9990PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993
9994 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009995 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009996 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009997 if (PyUnicode_READY(string) == -1) {
9998 Py_DECREF(string);
9999 return NULL;
10000 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010001
Benjamin Petersonead6b532011-12-20 17:23:42 -060010002 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010003 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010004 if (PyUnicode_IS_ASCII(string))
10005 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010006 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010007 PyUnicode_GET_LENGTH(string), keepends);
10008 else
10009 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010010 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010011 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 break;
10013 case PyUnicode_2BYTE_KIND:
10014 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010015 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 PyUnicode_GET_LENGTH(string), keepends);
10017 break;
10018 case PyUnicode_4BYTE_KIND:
10019 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010020 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010021 PyUnicode_GET_LENGTH(string), keepends);
10022 break;
10023 default:
10024 assert(0);
10025 list = 0;
10026 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027 Py_DECREF(string);
10028 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010029}
10030
Alexander Belopolsky40018472011-02-26 01:02:56 +000010031static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010032split(PyObject *self,
10033 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010034 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010035{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 int kind1, kind2, kind;
10037 void *buf1, *buf2;
10038 Py_ssize_t len1, len2;
10039 PyObject* out;
10040
Guido van Rossumd57fd912000-03-10 22:53:23 +000010041 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010042 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 if (PyUnicode_READY(self) == -1)
10045 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010048 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010050 if (PyUnicode_IS_ASCII(self))
10051 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010052 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010053 PyUnicode_GET_LENGTH(self), maxcount
10054 );
10055 else
10056 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010057 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010058 PyUnicode_GET_LENGTH(self), maxcount
10059 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 case PyUnicode_2BYTE_KIND:
10061 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010062 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 PyUnicode_GET_LENGTH(self), maxcount
10064 );
10065 case PyUnicode_4BYTE_KIND:
10066 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010067 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 PyUnicode_GET_LENGTH(self), maxcount
10069 );
10070 default:
10071 assert(0);
10072 return NULL;
10073 }
10074
10075 if (PyUnicode_READY(substring) == -1)
10076 return NULL;
10077
10078 kind1 = PyUnicode_KIND(self);
10079 kind2 = PyUnicode_KIND(substring);
10080 kind = kind1 > kind2 ? kind1 : kind2;
10081 buf1 = PyUnicode_DATA(self);
10082 buf2 = PyUnicode_DATA(substring);
10083 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010084 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 if (!buf1)
10086 return NULL;
10087 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 if (!buf2) {
10090 if (kind1 != kind) PyMem_Free(buf1);
10091 return NULL;
10092 }
10093 len1 = PyUnicode_GET_LENGTH(self);
10094 len2 = PyUnicode_GET_LENGTH(substring);
10095
Benjamin Petersonead6b532011-12-20 17:23:42 -060010096 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010097 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010098 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10099 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010100 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010101 else
10102 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010103 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 break;
10105 case PyUnicode_2BYTE_KIND:
10106 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010107 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 break;
10109 case PyUnicode_4BYTE_KIND:
10110 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 break;
10113 default:
10114 out = NULL;
10115 }
10116 if (kind1 != kind)
10117 PyMem_Free(buf1);
10118 if (kind2 != kind)
10119 PyMem_Free(buf2);
10120 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010121}
10122
Alexander Belopolsky40018472011-02-26 01:02:56 +000010123static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010124rsplit(PyObject *self,
10125 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010126 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010127{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 int kind1, kind2, kind;
10129 void *buf1, *buf2;
10130 Py_ssize_t len1, len2;
10131 PyObject* out;
10132
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010133 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010134 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 if (PyUnicode_READY(self) == -1)
10137 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010140 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010142 if (PyUnicode_IS_ASCII(self))
10143 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010144 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010145 PyUnicode_GET_LENGTH(self), maxcount
10146 );
10147 else
10148 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010149 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 PyUnicode_GET_LENGTH(self), maxcount
10151 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 case PyUnicode_2BYTE_KIND:
10153 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010154 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155 PyUnicode_GET_LENGTH(self), maxcount
10156 );
10157 case PyUnicode_4BYTE_KIND:
10158 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010159 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 PyUnicode_GET_LENGTH(self), maxcount
10161 );
10162 default:
10163 assert(0);
10164 return NULL;
10165 }
10166
10167 if (PyUnicode_READY(substring) == -1)
10168 return NULL;
10169
10170 kind1 = PyUnicode_KIND(self);
10171 kind2 = PyUnicode_KIND(substring);
10172 kind = kind1 > kind2 ? kind1 : kind2;
10173 buf1 = PyUnicode_DATA(self);
10174 buf2 = PyUnicode_DATA(substring);
10175 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (!buf1)
10178 return NULL;
10179 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 if (!buf2) {
10182 if (kind1 != kind) PyMem_Free(buf1);
10183 return NULL;
10184 }
10185 len1 = PyUnicode_GET_LENGTH(self);
10186 len2 = PyUnicode_GET_LENGTH(substring);
10187
Benjamin Petersonead6b532011-12-20 17:23:42 -060010188 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010190 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10191 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010193 else
10194 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 break;
10197 case PyUnicode_2BYTE_KIND:
10198 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010199 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 break;
10201 case PyUnicode_4BYTE_KIND:
10202 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010203 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 break;
10205 default:
10206 out = NULL;
10207 }
10208 if (kind1 != kind)
10209 PyMem_Free(buf1);
10210 if (kind2 != kind)
10211 PyMem_Free(buf2);
10212 return out;
10213}
10214
10215static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010216anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10217 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010219 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10222 return asciilib_find(buf1, len1, buf2, len2, offset);
10223 else
10224 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 case PyUnicode_2BYTE_KIND:
10226 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10227 case PyUnicode_4BYTE_KIND:
10228 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10229 }
10230 assert(0);
10231 return -1;
10232}
10233
10234static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10236 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010238 switch (kind) {
10239 case PyUnicode_1BYTE_KIND:
10240 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10241 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10242 else
10243 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10244 case PyUnicode_2BYTE_KIND:
10245 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10246 case PyUnicode_4BYTE_KIND:
10247 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10248 }
10249 assert(0);
10250 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010251}
10252
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010253static void
10254replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10255 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10256{
10257 int kind = PyUnicode_KIND(u);
10258 void *data = PyUnicode_DATA(u);
10259 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10260 if (kind == PyUnicode_1BYTE_KIND) {
10261 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10262 (Py_UCS1 *)data + len,
10263 u1, u2, maxcount);
10264 }
10265 else if (kind == PyUnicode_2BYTE_KIND) {
10266 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10267 (Py_UCS2 *)data + len,
10268 u1, u2, maxcount);
10269 }
10270 else {
10271 assert(kind == PyUnicode_4BYTE_KIND);
10272 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10273 (Py_UCS4 *)data + len,
10274 u1, u2, maxcount);
10275 }
10276}
10277
Alexander Belopolsky40018472011-02-26 01:02:56 +000010278static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279replace(PyObject *self, PyObject *str1,
10280 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 PyObject *u;
10283 char *sbuf = PyUnicode_DATA(self);
10284 char *buf1 = PyUnicode_DATA(str1);
10285 char *buf2 = PyUnicode_DATA(str2);
10286 int srelease = 0, release1 = 0, release2 = 0;
10287 int skind = PyUnicode_KIND(self);
10288 int kind1 = PyUnicode_KIND(str1);
10289 int kind2 = PyUnicode_KIND(str2);
10290 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10291 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10292 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010293 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010294 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010295
10296 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010297 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010299 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010300
Victor Stinner59de0ee2011-10-07 10:01:28 +020010301 if (str1 == str2)
10302 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303
Victor Stinner49a0a212011-10-12 23:46:10 +020010304 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010305 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10306 if (maxchar < maxchar_str1)
10307 /* substring too wide to be present */
10308 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010309 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10310 /* Replacing str1 with str2 may cause a maxchar reduction in the
10311 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010312 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010313 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010316 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010318 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010320 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010322 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010323
Victor Stinner69ed0f42013-04-09 21:48:24 +020010324 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010325 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010326 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010327 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010328 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010330 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010332
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010333 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10334 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010335 }
10336 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 int rkind = skind;
10338 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010339 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 if (kind1 < rkind) {
10342 /* widen substring */
10343 buf1 = _PyUnicode_AsKind(str1, rkind);
10344 if (!buf1) goto error;
10345 release1 = 1;
10346 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010347 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010348 if (i < 0)
10349 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 if (rkind > kind2) {
10351 /* widen replacement */
10352 buf2 = _PyUnicode_AsKind(str2, rkind);
10353 if (!buf2) goto error;
10354 release2 = 1;
10355 }
10356 else if (rkind < kind2) {
10357 /* widen self and buf1 */
10358 rkind = kind2;
10359 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010360 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 sbuf = _PyUnicode_AsKind(self, rkind);
10362 if (!sbuf) goto error;
10363 srelease = 1;
10364 buf1 = _PyUnicode_AsKind(str1, rkind);
10365 if (!buf1) goto error;
10366 release1 = 1;
10367 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010368 u = PyUnicode_New(slen, maxchar);
10369 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010371 assert(PyUnicode_KIND(u) == rkind);
10372 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010373
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010374 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010375 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010378 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010380
10381 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010382 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010383 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010384 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010385 if (i == -1)
10386 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010387 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010391 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010393 }
10394 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010396 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 int rkind = skind;
10398 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010401 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 buf1 = _PyUnicode_AsKind(str1, rkind);
10403 if (!buf1) goto error;
10404 release1 = 1;
10405 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010407 if (n == 0)
10408 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010410 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 buf2 = _PyUnicode_AsKind(str2, rkind);
10412 if (!buf2) goto error;
10413 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 rkind = kind2;
10418 sbuf = _PyUnicode_AsKind(self, rkind);
10419 if (!sbuf) goto error;
10420 srelease = 1;
10421 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010422 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 buf1 = _PyUnicode_AsKind(str1, rkind);
10424 if (!buf1) goto error;
10425 release1 = 1;
10426 }
10427 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10428 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010429 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 PyErr_SetString(PyExc_OverflowError,
10431 "replace string is too long");
10432 goto error;
10433 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010434 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010435 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010436 _Py_INCREF_UNICODE_EMPTY();
10437 if (!unicode_empty)
10438 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010439 u = unicode_empty;
10440 goto done;
10441 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010442 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 PyErr_SetString(PyExc_OverflowError,
10444 "replace string is too long");
10445 goto error;
10446 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010447 u = PyUnicode_New(new_size, maxchar);
10448 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010449 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 assert(PyUnicode_KIND(u) == rkind);
10451 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 ires = i = 0;
10453 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010454 while (n-- > 0) {
10455 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010456 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010457 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010458 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010459 if (j == -1)
10460 break;
10461 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010462 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010463 memcpy(res + rkind * ires,
10464 sbuf + rkind * i,
10465 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010467 }
10468 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010470 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010472 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010478 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010479 memcpy(res + rkind * ires,
10480 sbuf + rkind * i,
10481 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010482 }
10483 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010484 /* interleave */
10485 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010486 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010488 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010490 if (--n <= 0)
10491 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010492 memcpy(res + rkind * ires,
10493 sbuf + rkind * i,
10494 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 ires++;
10496 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010497 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010498 memcpy(res + rkind * ires,
10499 sbuf + rkind * i,
10500 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010502 }
10503
10504 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010505 unicode_adjust_maxchar(&u);
10506 if (u == NULL)
10507 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010509
10510 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 if (srelease)
10512 PyMem_FREE(sbuf);
10513 if (release1)
10514 PyMem_FREE(buf1);
10515 if (release2)
10516 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010517 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519
Benjamin Peterson29060642009-01-31 22:14:21 +000010520 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 if (srelease)
10523 PyMem_FREE(sbuf);
10524 if (release1)
10525 PyMem_FREE(buf1);
10526 if (release2)
10527 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010528 return unicode_result_unchanged(self);
10529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 error:
10531 if (srelease && sbuf)
10532 PyMem_FREE(sbuf);
10533 if (release1 && buf1)
10534 PyMem_FREE(buf1);
10535 if (release2 && buf2)
10536 PyMem_FREE(buf2);
10537 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010538}
10539
10540/* --- Unicode Object Methods --------------------------------------------- */
10541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010542PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010543 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544\n\
10545Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010546characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547
10548static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010549unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010551 if (PyUnicode_READY(self) == -1)
10552 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010553 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010554}
10555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010556PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010557 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558\n\
10559Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010560have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561
10562static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010563unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010564{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010565 if (PyUnicode_READY(self) == -1)
10566 return NULL;
10567 if (PyUnicode_GET_LENGTH(self) == 0)
10568 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010569 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570}
10571
Benjamin Petersond5890c82012-01-14 13:23:30 -050010572PyDoc_STRVAR(casefold__doc__,
10573 "S.casefold() -> str\n\
10574\n\
10575Return a version of S suitable for caseless comparisons.");
10576
10577static PyObject *
10578unicode_casefold(PyObject *self)
10579{
10580 if (PyUnicode_READY(self) == -1)
10581 return NULL;
10582 if (PyUnicode_IS_ASCII(self))
10583 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010584 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010585}
10586
10587
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010588/* Argument converter. Coerces to a single unicode character */
10589
10590static int
10591convert_uc(PyObject *obj, void *addr)
10592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010594 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010595
Benjamin Peterson14339b62009-01-31 16:36:08 +000010596 uniobj = PyUnicode_FromObject(obj);
10597 if (uniobj == NULL) {
10598 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010599 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010600 return 0;
10601 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010603 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010604 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010605 Py_DECREF(uniobj);
10606 return 0;
10607 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010609 Py_DECREF(uniobj);
10610 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010611}
10612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010613PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010614 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010616Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010617done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618
10619static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010620unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010622 Py_ssize_t marg, left;
10623 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 Py_UCS4 fillchar = ' ';
10625
Victor Stinnere9a29352011-10-01 02:14:59 +020010626 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628
Benjamin Petersonbac79492012-01-14 13:34:47 -050010629 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630 return NULL;
10631
Victor Stinnerc4b49542011-12-11 22:44:26 +010010632 if (PyUnicode_GET_LENGTH(self) >= width)
10633 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
Victor Stinnerc4b49542011-12-11 22:44:26 +010010635 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 left = marg / 2 + (marg & width & 1);
10637
Victor Stinner9310abb2011-10-05 00:59:23 +020010638 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639}
10640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641/* This function assumes that str1 and str2 are readied by the caller. */
10642
Marc-André Lemburge5034372000-08-08 08:04:29 +000010643static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010644unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010645{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010646#define COMPARE(TYPE1, TYPE2) \
10647 do { \
10648 TYPE1* p1 = (TYPE1 *)data1; \
10649 TYPE2* p2 = (TYPE2 *)data2; \
10650 TYPE1* end = p1 + len; \
10651 Py_UCS4 c1, c2; \
10652 for (; p1 != end; p1++, p2++) { \
10653 c1 = *p1; \
10654 c2 = *p2; \
10655 if (c1 != c2) \
10656 return (c1 < c2) ? -1 : 1; \
10657 } \
10658 } \
10659 while (0)
10660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 int kind1, kind2;
10662 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010663 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010665 kind1 = PyUnicode_KIND(str1);
10666 kind2 = PyUnicode_KIND(str2);
10667 data1 = PyUnicode_DATA(str1);
10668 data2 = PyUnicode_DATA(str2);
10669 len1 = PyUnicode_GET_LENGTH(str1);
10670 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010671 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010672
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010673 switch(kind1) {
10674 case PyUnicode_1BYTE_KIND:
10675 {
10676 switch(kind2) {
10677 case PyUnicode_1BYTE_KIND:
10678 {
10679 int cmp = memcmp(data1, data2, len);
10680 /* normalize result of memcmp() into the range [-1; 1] */
10681 if (cmp < 0)
10682 return -1;
10683 if (cmp > 0)
10684 return 1;
10685 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010686 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010687 case PyUnicode_2BYTE_KIND:
10688 COMPARE(Py_UCS1, Py_UCS2);
10689 break;
10690 case PyUnicode_4BYTE_KIND:
10691 COMPARE(Py_UCS1, Py_UCS4);
10692 break;
10693 default:
10694 assert(0);
10695 }
10696 break;
10697 }
10698 case PyUnicode_2BYTE_KIND:
10699 {
10700 switch(kind2) {
10701 case PyUnicode_1BYTE_KIND:
10702 COMPARE(Py_UCS2, Py_UCS1);
10703 break;
10704 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010705 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010706 COMPARE(Py_UCS2, Py_UCS2);
10707 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010708 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010709 case PyUnicode_4BYTE_KIND:
10710 COMPARE(Py_UCS2, Py_UCS4);
10711 break;
10712 default:
10713 assert(0);
10714 }
10715 break;
10716 }
10717 case PyUnicode_4BYTE_KIND:
10718 {
10719 switch(kind2) {
10720 case PyUnicode_1BYTE_KIND:
10721 COMPARE(Py_UCS4, Py_UCS1);
10722 break;
10723 case PyUnicode_2BYTE_KIND:
10724 COMPARE(Py_UCS4, Py_UCS2);
10725 break;
10726 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010727 {
10728#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10729 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10730 /* normalize result of wmemcmp() into the range [-1; 1] */
10731 if (cmp < 0)
10732 return -1;
10733 if (cmp > 0)
10734 return 1;
10735#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010736 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010737#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010738 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010739 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010740 default:
10741 assert(0);
10742 }
10743 break;
10744 }
10745 default:
10746 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010747 }
10748
Victor Stinner770e19e2012-10-04 22:59:45 +020010749 if (len1 == len2)
10750 return 0;
10751 if (len1 < len2)
10752 return -1;
10753 else
10754 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010755
10756#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010757}
10758
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010759Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010760unicode_compare_eq(PyObject *str1, PyObject *str2)
10761{
10762 int kind;
10763 void *data1, *data2;
10764 Py_ssize_t len;
10765 int cmp;
10766
Victor Stinnere5567ad2012-10-23 02:48:49 +020010767 len = PyUnicode_GET_LENGTH(str1);
10768 if (PyUnicode_GET_LENGTH(str2) != len)
10769 return 0;
10770 kind = PyUnicode_KIND(str1);
10771 if (PyUnicode_KIND(str2) != kind)
10772 return 0;
10773 data1 = PyUnicode_DATA(str1);
10774 data2 = PyUnicode_DATA(str2);
10775
10776 cmp = memcmp(data1, data2, len * kind);
10777 return (cmp == 0);
10778}
10779
10780
Alexander Belopolsky40018472011-02-26 01:02:56 +000010781int
10782PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10785 if (PyUnicode_READY(left) == -1 ||
10786 PyUnicode_READY(right) == -1)
10787 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010788
10789 /* a string is equal to itself */
10790 if (left == right)
10791 return 0;
10792
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010793 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010795 PyErr_Format(PyExc_TypeError,
10796 "Can't compare %.100s and %.100s",
10797 left->ob_type->tp_name,
10798 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799 return -1;
10800}
10801
Martin v. Löwis5b222132007-06-10 09:51:05 +000010802int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010803_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10804{
10805 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10806 if (right_str == NULL)
10807 return -1;
10808 return PyUnicode_Compare(left, right_str);
10809}
10810
10811int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010812PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 Py_ssize_t i;
10815 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 Py_UCS4 chr;
10817
Victor Stinner910337b2011-10-03 03:20:16 +020010818 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010819 if (PyUnicode_READY(uni) == -1)
10820 return -1;
10821 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010822 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010823 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010824 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010825 size_t len, len2 = strlen(str);
10826 int cmp;
10827
10828 len = Py_MIN(len1, len2);
10829 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010830 if (cmp != 0) {
10831 if (cmp < 0)
10832 return -1;
10833 else
10834 return 1;
10835 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010836 if (len1 > len2)
10837 return 1; /* uni is longer */
10838 if (len2 > len1)
10839 return -1; /* str is longer */
10840 return 0;
10841 }
10842 else {
10843 void *data = PyUnicode_DATA(uni);
10844 /* Compare Unicode string and source character set string */
10845 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10846 if (chr != str[i])
10847 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10848 /* This check keeps Python strings that end in '\0' from comparing equal
10849 to C strings identical up to that point. */
10850 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10851 return 1; /* uni is longer */
10852 if (str[i])
10853 return -1; /* str is longer */
10854 return 0;
10855 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010856}
10857
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010858
Benjamin Peterson29060642009-01-31 22:14:21 +000010859#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010860 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010861
Alexander Belopolsky40018472011-02-26 01:02:56 +000010862PyObject *
10863PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010864{
10865 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010866 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010867
Victor Stinnere5567ad2012-10-23 02:48:49 +020010868 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10869 Py_RETURN_NOTIMPLEMENTED;
10870
10871 if (PyUnicode_READY(left) == -1 ||
10872 PyUnicode_READY(right) == -1)
10873 return NULL;
10874
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010875 if (left == right) {
10876 switch (op) {
10877 case Py_EQ:
10878 case Py_LE:
10879 case Py_GE:
10880 /* a string is equal to itself */
10881 v = Py_True;
10882 break;
10883 case Py_NE:
10884 case Py_LT:
10885 case Py_GT:
10886 v = Py_False;
10887 break;
10888 default:
10889 PyErr_BadArgument();
10890 return NULL;
10891 }
10892 }
10893 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010894 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010895 result ^= (op == Py_NE);
10896 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010897 }
10898 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010899 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010900
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010901 /* Convert the return value to a Boolean */
10902 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010903 case Py_LE:
10904 v = TEST_COND(result <= 0);
10905 break;
10906 case Py_GE:
10907 v = TEST_COND(result >= 0);
10908 break;
10909 case Py_LT:
10910 v = TEST_COND(result == -1);
10911 break;
10912 case Py_GT:
10913 v = TEST_COND(result == 1);
10914 break;
10915 default:
10916 PyErr_BadArgument();
10917 return NULL;
10918 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010919 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010920 Py_INCREF(v);
10921 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010922}
10923
Alexander Belopolsky40018472011-02-26 01:02:56 +000010924int
10925PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010926{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010928 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 void *buf1, *buf2;
10930 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010931 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010932
10933 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010934 sub = PyUnicode_FromObject(element);
10935 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010936 PyErr_Format(PyExc_TypeError,
10937 "'in <string>' requires string as left operand, not %s",
10938 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010939 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010940 }
10941
Thomas Wouters477c8d52006-05-27 19:21:47 +000010942 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010943 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010944 Py_DECREF(sub);
10945 return -1;
10946 }
10947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010948 kind1 = PyUnicode_KIND(str);
10949 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 buf1 = PyUnicode_DATA(str);
10951 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010952 if (kind2 != kind1) {
10953 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010954 Py_DECREF(sub);
10955 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010956 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010957 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010958 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010960 if (!buf2) {
10961 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010962 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 return -1;
10964 }
10965 len1 = PyUnicode_GET_LENGTH(str);
10966 len2 = PyUnicode_GET_LENGTH(sub);
10967
Victor Stinner77282cb2013-04-14 19:22:47 +020010968 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010969 case PyUnicode_1BYTE_KIND:
10970 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10971 break;
10972 case PyUnicode_2BYTE_KIND:
10973 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10974 break;
10975 case PyUnicode_4BYTE_KIND:
10976 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10977 break;
10978 default:
10979 result = -1;
10980 assert(0);
10981 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010982
10983 Py_DECREF(str);
10984 Py_DECREF(sub);
10985
Victor Stinner77282cb2013-04-14 19:22:47 +020010986 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010987 PyMem_Free(buf2);
10988
Guido van Rossum403d68b2000-03-13 15:55:09 +000010989 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010990}
10991
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992/* Concat to string or Unicode object giving a new Unicode object. */
10993
Alexander Belopolsky40018472011-02-26 01:02:56 +000010994PyObject *
10995PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010998 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010999 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000
11001 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011002 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011004 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011005 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011007 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008
11009 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011010 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011011 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011014 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011015 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 }
11018
Victor Stinner488fa492011-12-12 00:01:39 +010011019 u_len = PyUnicode_GET_LENGTH(u);
11020 v_len = PyUnicode_GET_LENGTH(v);
11021 if (u_len > PY_SSIZE_T_MAX - v_len) {
11022 PyErr_SetString(PyExc_OverflowError,
11023 "strings are too large to concat");
11024 goto onError;
11025 }
11026 new_len = u_len + v_len;
11027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011028 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011029 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011030 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011031
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011033 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011035 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011036 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11037 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038 Py_DECREF(u);
11039 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011040 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011041 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042
Benjamin Peterson29060642009-01-31 22:14:21 +000011043 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044 Py_XDECREF(u);
11045 Py_XDECREF(v);
11046 return NULL;
11047}
11048
Walter Dörwald1ab83302007-05-18 17:15:44 +000011049void
Victor Stinner23e56682011-10-03 03:54:37 +020011050PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011051{
Victor Stinner23e56682011-10-03 03:54:37 +020011052 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011053 Py_UCS4 maxchar, maxchar2;
11054 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011055
11056 if (p_left == NULL) {
11057 if (!PyErr_Occurred())
11058 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011059 return;
11060 }
Victor Stinner23e56682011-10-03 03:54:37 +020011061 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011062 if (right == NULL || left == NULL
11063 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011064 if (!PyErr_Occurred())
11065 PyErr_BadInternalCall();
11066 goto error;
11067 }
11068
Benjamin Petersonbac79492012-01-14 13:34:47 -050011069 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011070 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011071 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011072 goto error;
11073
Victor Stinner488fa492011-12-12 00:01:39 +010011074 /* Shortcuts */
11075 if (left == unicode_empty) {
11076 Py_DECREF(left);
11077 Py_INCREF(right);
11078 *p_left = right;
11079 return;
11080 }
11081 if (right == unicode_empty)
11082 return;
11083
11084 left_len = PyUnicode_GET_LENGTH(left);
11085 right_len = PyUnicode_GET_LENGTH(right);
11086 if (left_len > PY_SSIZE_T_MAX - right_len) {
11087 PyErr_SetString(PyExc_OverflowError,
11088 "strings are too large to concat");
11089 goto error;
11090 }
11091 new_len = left_len + right_len;
11092
11093 if (unicode_modifiable(left)
11094 && PyUnicode_CheckExact(right)
11095 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011096 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11097 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011098 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011099 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011100 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11101 {
11102 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011103 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011104 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011105
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011106 /* copy 'right' into the newly allocated area of 'left' */
11107 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011108 }
Victor Stinner488fa492011-12-12 00:01:39 +010011109 else {
11110 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11111 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011112 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011113
Victor Stinner488fa492011-12-12 00:01:39 +010011114 /* Concat the two Unicode strings */
11115 res = PyUnicode_New(new_len, maxchar);
11116 if (res == NULL)
11117 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011118 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11119 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011120 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011121 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011122 }
11123 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011124 return;
11125
11126error:
Victor Stinner488fa492011-12-12 00:01:39 +010011127 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011128}
11129
11130void
11131PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011133 PyUnicode_Append(pleft, right);
11134 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011135}
11136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011137PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011138 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011140Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011141string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011142interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143
11144static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011145unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011147 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011148 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011149 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 int kind1, kind2, kind;
11152 void *buf1, *buf2;
11153 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154
Jesus Ceaac451502011-04-20 17:09:23 +020011155 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11156 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011157 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 kind1 = PyUnicode_KIND(self);
11160 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011161 if (kind2 > kind1) {
11162 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011163 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011164 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011165 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 buf1 = PyUnicode_DATA(self);
11167 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011169 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (!buf2) {
11171 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 return NULL;
11173 }
11174 len1 = PyUnicode_GET_LENGTH(self);
11175 len2 = PyUnicode_GET_LENGTH(substring);
11176
11177 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011178 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 case PyUnicode_1BYTE_KIND:
11180 iresult = ucs1lib_count(
11181 ((Py_UCS1*)buf1) + start, end - start,
11182 buf2, len2, PY_SSIZE_T_MAX
11183 );
11184 break;
11185 case PyUnicode_2BYTE_KIND:
11186 iresult = ucs2lib_count(
11187 ((Py_UCS2*)buf1) + start, end - start,
11188 buf2, len2, PY_SSIZE_T_MAX
11189 );
11190 break;
11191 case PyUnicode_4BYTE_KIND:
11192 iresult = ucs4lib_count(
11193 ((Py_UCS4*)buf1) + start, end - start,
11194 buf2, len2, PY_SSIZE_T_MAX
11195 );
11196 break;
11197 default:
11198 assert(0); iresult = 0;
11199 }
11200
11201 result = PyLong_FromSsize_t(iresult);
11202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 if (kind2 != kind)
11204 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
11206 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011207
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 return result;
11209}
11210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011211PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011212 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011214Encode S using the codec registered for encoding. Default encoding\n\
11215is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011216handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011217a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11218'xmlcharrefreplace' as well as any other name registered with\n\
11219codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220
11221static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011222unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011224 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 char *encoding = NULL;
11226 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011227
Benjamin Peterson308d6372009-09-18 21:42:35 +000011228 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11229 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011231 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011232}
11233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011234PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011235 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236\n\
11237Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011238If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239
11240static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011241unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011243 Py_ssize_t i, j, line_pos, src_len, incr;
11244 Py_UCS4 ch;
11245 PyObject *u;
11246 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011247 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011249 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011250 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251
Ezio Melotti745d54d2013-11-16 19:10:57 +020011252 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11253 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255
Antoine Pitrou22425222011-10-04 19:10:51 +020011256 if (PyUnicode_READY(self) == -1)
11257 return NULL;
11258
Thomas Wouters7e474022000-07-16 12:04:32 +000011259 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 src_len = PyUnicode_GET_LENGTH(self);
11261 i = j = line_pos = 0;
11262 kind = PyUnicode_KIND(self);
11263 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011264 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011265 for (; i < src_len; i++) {
11266 ch = PyUnicode_READ(kind, src_data, i);
11267 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011268 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011269 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011270 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011272 goto overflow;
11273 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011275 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011276 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011278 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011279 goto overflow;
11280 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011282 if (ch == '\n' || ch == '\r')
11283 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011285 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011286 if (!found)
11287 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011288
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011290 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 if (!u)
11292 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011293 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296
Antoine Pitroue71d5742011-10-04 15:55:09 +020011297 for (; i < src_len; i++) {
11298 ch = PyUnicode_READ(kind, src_data, i);
11299 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011301 incr = tabsize - (line_pos % tabsize);
11302 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011303 FILL(kind, dest_data, ' ', j, incr);
11304 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011305 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011306 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011307 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011308 line_pos++;
11309 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011310 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011311 if (ch == '\n' || ch == '\r')
11312 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011314 }
11315 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011316 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011317
Antoine Pitroue71d5742011-10-04 15:55:09 +020011318 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011319 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321}
11322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011324 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325\n\
11326Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011327such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328arguments start and end are interpreted as in slice notation.\n\
11329\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011330Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331
11332static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011333unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011335 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011336 Py_ssize_t start;
11337 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011338 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339
Jesus Ceaac451502011-04-20 17:09:23 +020011340 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11341 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
Christian Heimesd47802e2013-06-29 21:33:36 +020011344 if (PyUnicode_READY(self) == -1) {
11345 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011347 }
11348 if (PyUnicode_READY(substring) == -1) {
11349 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352
Victor Stinner7931d9a2011-11-04 00:22:48 +010011353 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354
11355 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (result == -2)
11358 return NULL;
11359
Christian Heimes217cfd12007-12-02 14:31:20 +000011360 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011361}
11362
11363static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011364unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011366 void *data;
11367 enum PyUnicode_Kind kind;
11368 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011369
11370 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11371 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011373 }
11374 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11375 PyErr_SetString(PyExc_IndexError, "string index out of range");
11376 return NULL;
11377 }
11378 kind = PyUnicode_KIND(self);
11379 data = PyUnicode_DATA(self);
11380 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011381 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382}
11383
Guido van Rossumc2504932007-09-18 19:42:40 +000011384/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011385 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011386static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011387unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388{
Guido van Rossumc2504932007-09-18 19:42:40 +000011389 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011390 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011391
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011392#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011393 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011394#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 if (_PyUnicode_HASH(self) != -1)
11396 return _PyUnicode_HASH(self);
11397 if (PyUnicode_READY(self) == -1)
11398 return -1;
11399 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011400 /*
11401 We make the hash of the empty string be 0, rather than using
11402 (prefix ^ suffix), since this slightly obfuscates the hash secret
11403 */
11404 if (len == 0) {
11405 _PyUnicode_HASH(self) = 0;
11406 return 0;
11407 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011408 x = _Py_HashBytes(PyUnicode_DATA(self),
11409 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011411 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412}
11413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011414PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011415 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011417Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418
11419static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011422 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011423 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011424 Py_ssize_t start;
11425 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Jesus Ceaac451502011-04-20 17:09:23 +020011427 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11428 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
Christian Heimesd47a0452013-06-29 21:21:37 +020011431 if (PyUnicode_READY(self) == -1) {
11432 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011434 }
11435 if (PyUnicode_READY(substring) == -1) {
11436 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011437 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439
Victor Stinner7931d9a2011-11-04 00:22:48 +010011440 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
11442 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (result == -2)
11445 return NULL;
11446
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447 if (result < 0) {
11448 PyErr_SetString(PyExc_ValueError, "substring not found");
11449 return NULL;
11450 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011451
Christian Heimes217cfd12007-12-02 14:31:20 +000011452 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453}
11454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011455PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011456 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011458Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011459at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460
11461static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011462unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 Py_ssize_t i, length;
11465 int kind;
11466 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 int cased;
11468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (PyUnicode_READY(self) == -1)
11470 return NULL;
11471 length = PyUnicode_GET_LENGTH(self);
11472 kind = PyUnicode_KIND(self);
11473 data = PyUnicode_DATA(self);
11474
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 if (length == 1)
11477 return PyBool_FromLong(
11478 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011480 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011481 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011483
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 for (i = 0; i < length; i++) {
11486 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011487
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11489 return PyBool_FromLong(0);
11490 else if (!cased && Py_UNICODE_ISLOWER(ch))
11491 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011493 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494}
11495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011496PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011499Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011500at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501
11502static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011503unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 Py_ssize_t i, length;
11506 int kind;
11507 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508 int cased;
11509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510 if (PyUnicode_READY(self) == -1)
11511 return NULL;
11512 length = PyUnicode_GET_LENGTH(self);
11513 kind = PyUnicode_KIND(self);
11514 data = PyUnicode_DATA(self);
11515
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 if (length == 1)
11518 return PyBool_FromLong(
11519 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011521 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011524
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 for (i = 0; i < length; i++) {
11527 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011528
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11530 return PyBool_FromLong(0);
11531 else if (!cased && Py_UNICODE_ISUPPER(ch))
11532 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011534 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535}
11536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011537PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011538 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011540Return True if S is a titlecased string and there is at least one\n\
11541character in S, i.e. upper- and titlecase characters may only\n\
11542follow uncased characters and lowercase characters only cased ones.\n\
11543Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
11545static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011546unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 Py_ssize_t i, length;
11549 int kind;
11550 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551 int cased, previous_is_cased;
11552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 if (PyUnicode_READY(self) == -1)
11554 return NULL;
11555 length = PyUnicode_GET_LENGTH(self);
11556 kind = PyUnicode_KIND(self);
11557 data = PyUnicode_DATA(self);
11558
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 if (length == 1) {
11561 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11562 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11563 (Py_UNICODE_ISUPPER(ch) != 0));
11564 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011566 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011568 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011569
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 cased = 0;
11571 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 for (i = 0; i < length; i++) {
11573 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011574
Benjamin Peterson29060642009-01-31 22:14:21 +000011575 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11576 if (previous_is_cased)
11577 return PyBool_FromLong(0);
11578 previous_is_cased = 1;
11579 cased = 1;
11580 }
11581 else if (Py_UNICODE_ISLOWER(ch)) {
11582 if (!previous_is_cased)
11583 return PyBool_FromLong(0);
11584 previous_is_cased = 1;
11585 cased = 1;
11586 }
11587 else
11588 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011590 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011596Return True if all characters in S are whitespace\n\
11597and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598
11599static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011600unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 Py_ssize_t i, length;
11603 int kind;
11604 void *data;
11605
11606 if (PyUnicode_READY(self) == -1)
11607 return NULL;
11608 length = PyUnicode_GET_LENGTH(self);
11609 kind = PyUnicode_KIND(self);
11610 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 if (length == 1)
11614 return PyBool_FromLong(
11615 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011617 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 for (i = 0; i < length; i++) {
11622 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011623 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011626 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627}
11628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011629PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011630 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011631\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011632Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011633and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011634
11635static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011636unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 Py_ssize_t i, length;
11639 int kind;
11640 void *data;
11641
11642 if (PyUnicode_READY(self) == -1)
11643 return NULL;
11644 length = PyUnicode_GET_LENGTH(self);
11645 kind = PyUnicode_KIND(self);
11646 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011647
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011648 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (length == 1)
11650 return PyBool_FromLong(
11651 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652
11653 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 for (i = 0; i < length; i++) {
11658 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011660 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011661 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011662}
11663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011666\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011667Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011668and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011669
11670static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011671unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 int kind;
11674 void *data;
11675 Py_ssize_t len, i;
11676
11677 if (PyUnicode_READY(self) == -1)
11678 return NULL;
11679
11680 kind = PyUnicode_KIND(self);
11681 data = PyUnicode_DATA(self);
11682 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011684 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 if (len == 1) {
11686 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11687 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11688 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011689
11690 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011691 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 for (i = 0; i < len; i++) {
11695 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011696 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011698 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011699 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011700}
11701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011702PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011703 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011705Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011706False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
11708static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011709unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 Py_ssize_t i, length;
11712 int kind;
11713 void *data;
11714
11715 if (PyUnicode_READY(self) == -1)
11716 return NULL;
11717 length = PyUnicode_GET_LENGTH(self);
11718 kind = PyUnicode_KIND(self);
11719 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 1)
11723 return PyBool_FromLong(
11724 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011726 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011727 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 for (i = 0; i < length; i++) {
11731 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011734 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735}
11736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011738 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011740Return True if all characters in S are digits\n\
11741and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
11743static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011744unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 Py_ssize_t i, length;
11747 int kind;
11748 void *data;
11749
11750 if (PyUnicode_READY(self) == -1)
11751 return NULL;
11752 length = PyUnicode_GET_LENGTH(self);
11753 kind = PyUnicode_KIND(self);
11754 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (length == 1) {
11758 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11759 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11760 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011762 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 for (i = 0; i < length; i++) {
11767 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011770 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771}
11772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011773PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011774 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011776Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011777False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778
11779static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011780unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 Py_ssize_t i, length;
11783 int kind;
11784 void *data;
11785
11786 if (PyUnicode_READY(self) == -1)
11787 return NULL;
11788 length = PyUnicode_GET_LENGTH(self);
11789 kind = PyUnicode_KIND(self);
11790 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 if (length == 1)
11794 return PyBool_FromLong(
11795 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011797 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011801 for (i = 0; i < length; i++) {
11802 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011803 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011805 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806}
11807
Martin v. Löwis47383402007-08-15 07:32:56 +000011808int
11809PyUnicode_IsIdentifier(PyObject *self)
11810{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 int kind;
11812 void *data;
11813 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011814 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011815
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 if (PyUnicode_READY(self) == -1) {
11817 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 }
11820
11821 /* Special case for empty strings */
11822 if (PyUnicode_GET_LENGTH(self) == 0)
11823 return 0;
11824 kind = PyUnicode_KIND(self);
11825 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011826
11827 /* PEP 3131 says that the first character must be in
11828 XID_Start and subsequent characters in XID_Continue,
11829 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011830 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011831 letters, digits, underscore). However, given the current
11832 definition of XID_Start and XID_Continue, it is sufficient
11833 to check just for these, except that _ must be allowed
11834 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011836 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011837 return 0;
11838
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011839 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011841 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011842 return 1;
11843}
11844
11845PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011846 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011847\n\
11848Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011849to the language definition.\n\
11850\n\
11851Use keyword.iskeyword() to test for reserved identifiers\n\
11852such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011853
11854static PyObject*
11855unicode_isidentifier(PyObject *self)
11856{
11857 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11858}
11859
Georg Brandl559e5d72008-06-11 18:37:52 +000011860PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011861 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011862\n\
11863Return True if all characters in S are considered\n\
11864printable in repr() or S is empty, False otherwise.");
11865
11866static PyObject*
11867unicode_isprintable(PyObject *self)
11868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 Py_ssize_t i, length;
11870 int kind;
11871 void *data;
11872
11873 if (PyUnicode_READY(self) == -1)
11874 return NULL;
11875 length = PyUnicode_GET_LENGTH(self);
11876 kind = PyUnicode_KIND(self);
11877 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011878
11879 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 if (length == 1)
11881 return PyBool_FromLong(
11882 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 for (i = 0; i < length; i++) {
11885 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011886 Py_RETURN_FALSE;
11887 }
11888 }
11889 Py_RETURN_TRUE;
11890}
11891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011892PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011893 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894\n\
11895Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011896iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897
11898static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011899unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011901 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902}
11903
Martin v. Löwis18e16552006-02-15 17:27:45 +000011904static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011905unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (PyUnicode_READY(self) == -1)
11908 return -1;
11909 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910}
11911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011912PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011913 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011915Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011916done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917
11918static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011919unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011921 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 Py_UCS4 fillchar = ' ';
11923
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011924 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925 return NULL;
11926
Benjamin Petersonbac79492012-01-14 13:34:47 -050011927 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011928 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929
Victor Stinnerc4b49542011-12-11 22:44:26 +010011930 if (PyUnicode_GET_LENGTH(self) >= width)
11931 return unicode_result_unchanged(self);
11932
11933 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934}
11935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011936PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011939Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940
11941static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011942unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011944 if (PyUnicode_READY(self) == -1)
11945 return NULL;
11946 if (PyUnicode_IS_ASCII(self))
11947 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011948 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949}
11950
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951#define LEFTSTRIP 0
11952#define RIGHTSTRIP 1
11953#define BOTHSTRIP 2
11954
11955/* Arrays indexed by above */
11956static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11957
11958#define STRIPNAME(i) (stripformat[i]+3)
11959
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011960/* externally visible for str.strip(unicode) */
11961PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011962_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 void *data;
11965 int kind;
11966 Py_ssize_t i, j, len;
11967 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011968 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11971 return NULL;
11972
11973 kind = PyUnicode_KIND(self);
11974 data = PyUnicode_DATA(self);
11975 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011976 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11978 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011979 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011980
Benjamin Peterson14339b62009-01-31 16:36:08 +000011981 i = 0;
11982 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011983 while (i < len) {
11984 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11985 if (!BLOOM(sepmask, ch))
11986 break;
11987 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11988 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011989 i++;
11990 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011991 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011992
Benjamin Peterson14339b62009-01-31 16:36:08 +000011993 j = len;
11994 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011995 j--;
11996 while (j >= i) {
11997 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11998 if (!BLOOM(sepmask, ch))
11999 break;
12000 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12001 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012003 }
12004
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012006 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012007
Victor Stinner7931d9a2011-11-04 00:22:48 +010012008 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009}
12010
12011PyObject*
12012PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12013{
12014 unsigned char *data;
12015 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012016 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017
Victor Stinnerde636f32011-10-01 03:55:54 +020012018 if (PyUnicode_READY(self) == -1)
12019 return NULL;
12020
Victor Stinner684d5fd2012-05-03 02:32:34 +020012021 length = PyUnicode_GET_LENGTH(self);
12022 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012023
Victor Stinner684d5fd2012-05-03 02:32:34 +020012024 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012025 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026
Victor Stinnerde636f32011-10-01 03:55:54 +020012027 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012028 PyErr_SetString(PyExc_IndexError, "string index out of range");
12029 return NULL;
12030 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012031 if (start >= length || end < start)
12032 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012033
Victor Stinner684d5fd2012-05-03 02:32:34 +020012034 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012035 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012036 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012037 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012038 }
12039 else {
12040 kind = PyUnicode_KIND(self);
12041 data = PyUnicode_1BYTE_DATA(self);
12042 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012043 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012044 length);
12045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047
12048static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012049do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 Py_ssize_t len, i, j;
12052
12053 if (PyUnicode_READY(self) == -1)
12054 return NULL;
12055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012056 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012057
Victor Stinnercc7af722013-04-09 22:39:24 +020012058 if (PyUnicode_IS_ASCII(self)) {
12059 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12060
12061 i = 0;
12062 if (striptype != RIGHTSTRIP) {
12063 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012064 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012065 if (!_Py_ascii_whitespace[ch])
12066 break;
12067 i++;
12068 }
12069 }
12070
12071 j = len;
12072 if (striptype != LEFTSTRIP) {
12073 j--;
12074 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012075 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012076 if (!_Py_ascii_whitespace[ch])
12077 break;
12078 j--;
12079 }
12080 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012081 }
12082 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012083 else {
12084 int kind = PyUnicode_KIND(self);
12085 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012086
Victor Stinnercc7af722013-04-09 22:39:24 +020012087 i = 0;
12088 if (striptype != RIGHTSTRIP) {
12089 while (i < len) {
12090 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12091 if (!Py_UNICODE_ISSPACE(ch))
12092 break;
12093 i++;
12094 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012095 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012096
12097 j = len;
12098 if (striptype != LEFTSTRIP) {
12099 j--;
12100 while (j >= i) {
12101 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12102 if (!Py_UNICODE_ISSPACE(ch))
12103 break;
12104 j--;
12105 }
12106 j++;
12107 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012108 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012109
Victor Stinner7931d9a2011-11-04 00:22:48 +010012110 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012111}
12112
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012113
12114static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012115do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012116{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012117 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012118
Serhiy Storchakac6792272013-10-19 21:03:34 +030012119 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012120 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012121
Benjamin Peterson14339b62009-01-31 16:36:08 +000012122 if (sep != NULL && sep != Py_None) {
12123 if (PyUnicode_Check(sep))
12124 return _PyUnicode_XStrip(self, striptype, sep);
12125 else {
12126 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012127 "%s arg must be None or str",
12128 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012129 return NULL;
12130 }
12131 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012132
Benjamin Peterson14339b62009-01-31 16:36:08 +000012133 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134}
12135
12136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012137PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012139\n\
12140Return a copy of the string S with leading and trailing\n\
12141whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012142If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012143
12144static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012145unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012146{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012147 if (PyTuple_GET_SIZE(args) == 0)
12148 return do_strip(self, BOTHSTRIP); /* Common case */
12149 else
12150 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012151}
12152
12153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012154PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012155 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012156\n\
12157Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012158If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012159
12160static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012161unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012162{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012163 if (PyTuple_GET_SIZE(args) == 0)
12164 return do_strip(self, LEFTSTRIP); /* Common case */
12165 else
12166 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012167}
12168
12169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012170PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012171 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012172\n\
12173Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012174If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012175
12176static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012177unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012179 if (PyTuple_GET_SIZE(args) == 0)
12180 return do_strip(self, RIGHTSTRIP); /* Common case */
12181 else
12182 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012183}
12184
12185
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012187unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012189 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191
Serhiy Storchaka05997252013-01-26 12:14:02 +020012192 if (len < 1)
12193 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194
Victor Stinnerc4b49542011-12-11 22:44:26 +010012195 /* no repeat, return original string */
12196 if (len == 1)
12197 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012198
Benjamin Petersonbac79492012-01-14 13:34:47 -050012199 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 return NULL;
12201
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012202 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012203 PyErr_SetString(PyExc_OverflowError,
12204 "repeated string is too long");
12205 return NULL;
12206 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012208
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012209 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210 if (!u)
12211 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012212 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (PyUnicode_GET_LENGTH(str) == 1) {
12215 const int kind = PyUnicode_KIND(str);
12216 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012217 if (kind == PyUnicode_1BYTE_KIND) {
12218 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012219 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012220 }
12221 else if (kind == PyUnicode_2BYTE_KIND) {
12222 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012223 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012224 ucs2[n] = fill_char;
12225 } else {
12226 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12227 assert(kind == PyUnicode_4BYTE_KIND);
12228 for (n = 0; n < len; ++n)
12229 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 }
12232 else {
12233 /* number of characters copied this far */
12234 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012235 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 char *to = (char *) PyUnicode_DATA(u);
12237 Py_MEMCPY(to, PyUnicode_DATA(str),
12238 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012239 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012240 n = (done <= nchars-done) ? done : nchars-done;
12241 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012243 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244 }
12245
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012246 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012247 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248}
12249
Alexander Belopolsky40018472011-02-26 01:02:56 +000012250PyObject *
12251PyUnicode_Replace(PyObject *obj,
12252 PyObject *subobj,
12253 PyObject *replobj,
12254 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255{
12256 PyObject *self;
12257 PyObject *str1;
12258 PyObject *str2;
12259 PyObject *result;
12260
12261 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012262 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012263 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012265 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 Py_DECREF(self);
12267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268 }
12269 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012270 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012271 Py_DECREF(self);
12272 Py_DECREF(str1);
12273 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012275 if (PyUnicode_READY(self) == -1 ||
12276 PyUnicode_READY(str1) == -1 ||
12277 PyUnicode_READY(str2) == -1)
12278 result = NULL;
12279 else
12280 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 Py_DECREF(self);
12282 Py_DECREF(str1);
12283 Py_DECREF(str2);
12284 return result;
12285}
12286
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012287PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012288 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289\n\
12290Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012291old replaced by new. If the optional argument count is\n\
12292given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293
12294static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 PyObject *str1;
12298 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012299 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300 PyObject *result;
12301
Martin v. Löwis18e16552006-02-15 17:27:45 +000012302 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012304 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012305 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012306 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012307 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 return NULL;
12309 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012310 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012311 Py_DECREF(str1);
12312 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012313 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012314 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12315 result = NULL;
12316 else
12317 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318
12319 Py_DECREF(str1);
12320 Py_DECREF(str2);
12321 return result;
12322}
12323
Alexander Belopolsky40018472011-02-26 01:02:56 +000012324static PyObject *
12325unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012326{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012327 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 Py_ssize_t isize;
12329 Py_ssize_t osize, squote, dquote, i, o;
12330 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012331 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012335 return NULL;
12336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 isize = PyUnicode_GET_LENGTH(unicode);
12338 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 /* Compute length of output, quote characters, and
12341 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012342 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 max = 127;
12344 squote = dquote = 0;
12345 ikind = PyUnicode_KIND(unicode);
12346 for (i = 0; i < isize; i++) {
12347 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012348 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012350 case '\'': squote++; break;
12351 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012353 incr = 2;
12354 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 default:
12356 /* Fast-path ASCII */
12357 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012358 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012360 ;
12361 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012364 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012366 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012368 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012370 if (osize > PY_SSIZE_T_MAX - incr) {
12371 PyErr_SetString(PyExc_OverflowError,
12372 "string is too long to generate repr");
12373 return NULL;
12374 }
12375 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012376 }
12377
12378 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012379 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012381 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 if (dquote)
12383 /* Both squote and dquote present. Use squote,
12384 and escape them */
12385 osize += squote;
12386 else
12387 quote = '"';
12388 }
Victor Stinner55c08782013-04-14 18:45:39 +020012389 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390
12391 repr = PyUnicode_New(osize, max);
12392 if (repr == NULL)
12393 return NULL;
12394 okind = PyUnicode_KIND(repr);
12395 odata = PyUnicode_DATA(repr);
12396
12397 PyUnicode_WRITE(okind, odata, 0, quote);
12398 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012399 if (unchanged) {
12400 _PyUnicode_FastCopyCharacters(repr, 1,
12401 unicode, 0,
12402 isize);
12403 }
12404 else {
12405 for (i = 0, o = 1; i < isize; i++) {
12406 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012407
Victor Stinner55c08782013-04-14 18:45:39 +020012408 /* Escape quotes and backslashes */
12409 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012410 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012411 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012412 continue;
12413 }
12414
12415 /* Map special whitespace to '\t', \n', '\r' */
12416 if (ch == '\t') {
12417 PyUnicode_WRITE(okind, odata, o++, '\\');
12418 PyUnicode_WRITE(okind, odata, o++, 't');
12419 }
12420 else if (ch == '\n') {
12421 PyUnicode_WRITE(okind, odata, o++, '\\');
12422 PyUnicode_WRITE(okind, odata, o++, 'n');
12423 }
12424 else if (ch == '\r') {
12425 PyUnicode_WRITE(okind, odata, o++, '\\');
12426 PyUnicode_WRITE(okind, odata, o++, 'r');
12427 }
12428
12429 /* Map non-printable US ASCII to '\xhh' */
12430 else if (ch < ' ' || ch == 0x7F) {
12431 PyUnicode_WRITE(okind, odata, o++, '\\');
12432 PyUnicode_WRITE(okind, odata, o++, 'x');
12433 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12434 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12435 }
12436
12437 /* Copy ASCII characters as-is */
12438 else if (ch < 0x7F) {
12439 PyUnicode_WRITE(okind, odata, o++, ch);
12440 }
12441
12442 /* Non-ASCII characters */
12443 else {
12444 /* Map Unicode whitespace and control characters
12445 (categories Z* and C* except ASCII space)
12446 */
12447 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12448 PyUnicode_WRITE(okind, odata, o++, '\\');
12449 /* Map 8-bit characters to '\xhh' */
12450 if (ch <= 0xff) {
12451 PyUnicode_WRITE(okind, odata, o++, 'x');
12452 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12453 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12454 }
12455 /* Map 16-bit characters to '\uxxxx' */
12456 else if (ch <= 0xffff) {
12457 PyUnicode_WRITE(okind, odata, o++, 'u');
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12461 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12462 }
12463 /* Map 21-bit characters to '\U00xxxxxx' */
12464 else {
12465 PyUnicode_WRITE(okind, odata, o++, 'U');
12466 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12467 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12469 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12470 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12471 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12472 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12473 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12474 }
12475 }
12476 /* Copy characters as-is */
12477 else {
12478 PyUnicode_WRITE(okind, odata, o++, ch);
12479 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012480 }
12481 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012482 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012483 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012484 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012485 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012486}
12487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012488PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490\n\
12491Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012492such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493arguments start and end are interpreted as in slice notation.\n\
12494\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012495Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496
12497static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012500 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012501 Py_ssize_t start;
12502 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012503 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504
Jesus Ceaac451502011-04-20 17:09:23 +020012505 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12506 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012507 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508
Christian Heimesea71a522013-06-29 21:17:34 +020012509 if (PyUnicode_READY(self) == -1) {
12510 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012512 }
12513 if (PyUnicode_READY(substring) == -1) {
12514 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012515 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517
Victor Stinner7931d9a2011-11-04 00:22:48 +010012518 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519
12520 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 if (result == -2)
12523 return NULL;
12524
Christian Heimes217cfd12007-12-02 14:31:20 +000012525 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526}
12527
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012528PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012529 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012531Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532
12533static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012534unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012536 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012537 Py_ssize_t start;
12538 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012539 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540
Jesus Ceaac451502011-04-20 17:09:23 +020012541 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12542 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012543 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544
Christian Heimesea71a522013-06-29 21:17:34 +020012545 if (PyUnicode_READY(self) == -1) {
12546 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012548 }
12549 if (PyUnicode_READY(substring) == -1) {
12550 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012551 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553
Victor Stinner7931d9a2011-11-04 00:22:48 +010012554 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012555
12556 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 if (result == -2)
12559 return NULL;
12560
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561 if (result < 0) {
12562 PyErr_SetString(PyExc_ValueError, "substring not found");
12563 return NULL;
12564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565
Christian Heimes217cfd12007-12-02 14:31:20 +000012566 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012567}
12568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012569PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012570 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012571\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012572Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012573done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574
12575static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012576unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012578 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 Py_UCS4 fillchar = ' ';
12580
Victor Stinnere9a29352011-10-01 02:14:59 +020012581 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012583
Benjamin Petersonbac79492012-01-14 13:34:47 -050012584 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585 return NULL;
12586
Victor Stinnerc4b49542011-12-11 22:44:26 +010012587 if (PyUnicode_GET_LENGTH(self) >= width)
12588 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589
Victor Stinnerc4b49542011-12-11 22:44:26 +010012590 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591}
12592
Alexander Belopolsky40018472011-02-26 01:02:56 +000012593PyObject *
12594PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595{
12596 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012597
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598 s = PyUnicode_FromObject(s);
12599 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012600 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012601 if (sep != NULL) {
12602 sep = PyUnicode_FromObject(sep);
12603 if (sep == NULL) {
12604 Py_DECREF(s);
12605 return NULL;
12606 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607 }
12608
Victor Stinner9310abb2011-10-05 00:59:23 +020012609 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610
12611 Py_DECREF(s);
12612 Py_XDECREF(sep);
12613 return result;
12614}
12615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012616PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012617 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618\n\
12619Return a list of the words in S, using sep as the\n\
12620delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012621splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012622whitespace string is a separator and empty strings are\n\
12623removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624
12625static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012626unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012628 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012630 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012632 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12633 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634 return NULL;
12635
12636 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012637 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012639 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012641 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642}
12643
Thomas Wouters477c8d52006-05-27 19:21:47 +000012644PyObject *
12645PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12646{
12647 PyObject* str_obj;
12648 PyObject* sep_obj;
12649 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012650 int kind1, kind2, kind;
12651 void *buf1 = NULL, *buf2 = NULL;
12652 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012653
12654 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012655 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012656 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012657 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012658 if (!sep_obj) {
12659 Py_DECREF(str_obj);
12660 return NULL;
12661 }
12662 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12663 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012664 Py_DECREF(str_obj);
12665 return NULL;
12666 }
12667
Victor Stinner14f8f022011-10-05 20:58:25 +020012668 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012669 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012670 kind = Py_MAX(kind1, kind2);
12671 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012673 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 if (!buf1)
12675 goto onError;
12676 buf2 = PyUnicode_DATA(sep_obj);
12677 if (kind2 != kind)
12678 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12679 if (!buf2)
12680 goto onError;
12681 len1 = PyUnicode_GET_LENGTH(str_obj);
12682 len2 = PyUnicode_GET_LENGTH(sep_obj);
12683
Benjamin Petersonead6b532011-12-20 17:23:42 -060012684 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012685 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012686 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12687 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12688 else
12689 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012690 break;
12691 case PyUnicode_2BYTE_KIND:
12692 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12693 break;
12694 case PyUnicode_4BYTE_KIND:
12695 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12696 break;
12697 default:
12698 assert(0);
12699 out = 0;
12700 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012701
12702 Py_DECREF(sep_obj);
12703 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 if (kind1 != kind)
12705 PyMem_Free(buf1);
12706 if (kind2 != kind)
12707 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012708
12709 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 onError:
12711 Py_DECREF(sep_obj);
12712 Py_DECREF(str_obj);
12713 if (kind1 != kind && buf1)
12714 PyMem_Free(buf1);
12715 if (kind2 != kind && buf2)
12716 PyMem_Free(buf2);
12717 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012718}
12719
12720
12721PyObject *
12722PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12723{
12724 PyObject* str_obj;
12725 PyObject* sep_obj;
12726 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 int kind1, kind2, kind;
12728 void *buf1 = NULL, *buf2 = NULL;
12729 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012730
12731 str_obj = PyUnicode_FromObject(str_in);
12732 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012734 sep_obj = PyUnicode_FromObject(sep_in);
12735 if (!sep_obj) {
12736 Py_DECREF(str_obj);
12737 return NULL;
12738 }
12739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 kind1 = PyUnicode_KIND(str_in);
12741 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012742 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 buf1 = PyUnicode_DATA(str_in);
12744 if (kind1 != kind)
12745 buf1 = _PyUnicode_AsKind(str_in, kind);
12746 if (!buf1)
12747 goto onError;
12748 buf2 = PyUnicode_DATA(sep_obj);
12749 if (kind2 != kind)
12750 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12751 if (!buf2)
12752 goto onError;
12753 len1 = PyUnicode_GET_LENGTH(str_obj);
12754 len2 = PyUnicode_GET_LENGTH(sep_obj);
12755
Benjamin Petersonead6b532011-12-20 17:23:42 -060012756 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012757 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012758 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12759 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12760 else
12761 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 break;
12763 case PyUnicode_2BYTE_KIND:
12764 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12765 break;
12766 case PyUnicode_4BYTE_KIND:
12767 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12768 break;
12769 default:
12770 assert(0);
12771 out = 0;
12772 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012773
12774 Py_DECREF(sep_obj);
12775 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012776 if (kind1 != kind)
12777 PyMem_Free(buf1);
12778 if (kind2 != kind)
12779 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012780
12781 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782 onError:
12783 Py_DECREF(sep_obj);
12784 Py_DECREF(str_obj);
12785 if (kind1 != kind && buf1)
12786 PyMem_Free(buf1);
12787 if (kind2 != kind && buf2)
12788 PyMem_Free(buf2);
12789 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012790}
12791
12792PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012793 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012794\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012795Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012796the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012797found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798
12799static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012800unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801{
Victor Stinner9310abb2011-10-05 00:59:23 +020012802 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803}
12804
12805PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012806 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012808Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012809the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012810separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012811
12812static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012813unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012814{
Victor Stinner9310abb2011-10-05 00:59:23 +020012815 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012816}
12817
Alexander Belopolsky40018472011-02-26 01:02:56 +000012818PyObject *
12819PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012820{
12821 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012822
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012823 s = PyUnicode_FromObject(s);
12824 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012825 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 if (sep != NULL) {
12827 sep = PyUnicode_FromObject(sep);
12828 if (sep == NULL) {
12829 Py_DECREF(s);
12830 return NULL;
12831 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012832 }
12833
Victor Stinner9310abb2011-10-05 00:59:23 +020012834 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012835
12836 Py_DECREF(s);
12837 Py_XDECREF(sep);
12838 return result;
12839}
12840
12841PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012842 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012843\n\
12844Return a list of the words in S, using sep as the\n\
12845delimiter string, starting at the end of the string and\n\
12846working to the front. If maxsplit is given, at most maxsplit\n\
12847splits are done. If sep is not specified, any whitespace string\n\
12848is a separator.");
12849
12850static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012851unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012852{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012853 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012854 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012855 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012856
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012857 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12858 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012859 return NULL;
12860
12861 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012863 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012864 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012865 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012866 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012867}
12868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012869PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012870 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871\n\
12872Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012873Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012874is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875
12876static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012877unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012879 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012880 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012882 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12883 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884 return NULL;
12885
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012886 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887}
12888
12889static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012890PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012892 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893}
12894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012895PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897\n\
12898Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012899and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900
12901static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012902unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012904 if (PyUnicode_READY(self) == -1)
12905 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012906 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907}
12908
Larry Hastings61272b72014-01-07 12:41:53 -080012909/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012910
Larry Hastings31826802013-10-19 00:09:25 -070012911@staticmethod
12912str.maketrans as unicode_maketrans
12913
12914 x: object
12915
12916 y: unicode=NULL
12917
12918 z: unicode=NULL
12919
12920 /
12921
12922Return a translation table usable for str.translate().
12923
12924If there is only one argument, it must be a dictionary mapping Unicode
12925ordinals (integers) or characters to Unicode ordinals, strings or None.
12926Character keys will be then converted to ordinals.
12927If there are two arguments, they must be strings of equal length, and
12928in the resulting dictionary, each character in x will be mapped to the
12929character at the same position in y. If there is a third argument, it
12930must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012931[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012932
12933PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012934"maketrans(x, y=None, z=None, /)\n"
12935"--\n"
12936"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012937"Return a translation table usable for str.translate().\n"
12938"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012939"If there is only one argument, it must be a dictionary mapping Unicode\n"
12940"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12941"Character keys will be then converted to ordinals.\n"
12942"If there are two arguments, they must be strings of equal length, and\n"
12943"in the resulting dictionary, each character in x will be mapped to the\n"
12944"character at the same position in y. If there is a third argument, it\n"
12945"must be a string, whose characters will be mapped to None in the result.");
12946
12947#define UNICODE_MAKETRANS_METHODDEF \
12948 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12949
12950static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012951unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012952
12953static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012954unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012955{
Larry Hastings31826802013-10-19 00:09:25 -070012956 PyObject *return_value = NULL;
12957 PyObject *x;
12958 PyObject *y = NULL;
12959 PyObject *z = NULL;
12960
12961 if (!PyArg_ParseTuple(args,
12962 "O|UU:maketrans",
12963 &x, &y, &z))
12964 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012965 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012966
12967exit:
12968 return return_value;
12969}
12970
12971static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012972unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012973/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012974{
Georg Brandlceee0772007-11-27 23:48:05 +000012975 PyObject *new = NULL, *key, *value;
12976 Py_ssize_t i = 0;
12977 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012978
Georg Brandlceee0772007-11-27 23:48:05 +000012979 new = PyDict_New();
12980 if (!new)
12981 return NULL;
12982 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 int x_kind, y_kind, z_kind;
12984 void *x_data, *y_data, *z_data;
12985
Georg Brandlceee0772007-11-27 23:48:05 +000012986 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012987 if (!PyUnicode_Check(x)) {
12988 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12989 "be a string if there is a second argument");
12990 goto err;
12991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012993 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12994 "arguments must have equal length");
12995 goto err;
12996 }
12997 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012998 x_kind = PyUnicode_KIND(x);
12999 y_kind = PyUnicode_KIND(y);
13000 x_data = PyUnicode_DATA(x);
13001 y_data = PyUnicode_DATA(y);
13002 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13003 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013004 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013005 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013006 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013007 if (!value) {
13008 Py_DECREF(key);
13009 goto err;
13010 }
Georg Brandlceee0772007-11-27 23:48:05 +000013011 res = PyDict_SetItem(new, key, value);
13012 Py_DECREF(key);
13013 Py_DECREF(value);
13014 if (res < 0)
13015 goto err;
13016 }
13017 /* create entries for deleting chars in z */
13018 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013019 z_kind = PyUnicode_KIND(z);
13020 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013021 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013022 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013023 if (!key)
13024 goto err;
13025 res = PyDict_SetItem(new, key, Py_None);
13026 Py_DECREF(key);
13027 if (res < 0)
13028 goto err;
13029 }
13030 }
13031 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013032 int kind;
13033 void *data;
13034
Georg Brandlceee0772007-11-27 23:48:05 +000013035 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013036 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013037 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13038 "to maketrans it must be a dict");
13039 goto err;
13040 }
13041 /* copy entries into the new dict, converting string keys to int keys */
13042 while (PyDict_Next(x, &i, &key, &value)) {
13043 if (PyUnicode_Check(key)) {
13044 /* convert string keys to integer keys */
13045 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013046 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013047 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13048 "table must be of length 1");
13049 goto err;
13050 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013051 kind = PyUnicode_KIND(key);
13052 data = PyUnicode_DATA(key);
13053 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013054 if (!newkey)
13055 goto err;
13056 res = PyDict_SetItem(new, newkey, value);
13057 Py_DECREF(newkey);
13058 if (res < 0)
13059 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013060 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013061 /* just keep integer keys */
13062 if (PyDict_SetItem(new, key, value) < 0)
13063 goto err;
13064 } else {
13065 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13066 "be strings or integers");
13067 goto err;
13068 }
13069 }
13070 }
13071 return new;
13072 err:
13073 Py_DECREF(new);
13074 return NULL;
13075}
13076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013077PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079\n\
13080Return a copy of the string S, where all characters have been mapped\n\
13081through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013082Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013083Unmapped characters are left untouched. Characters mapped to None\n\
13084are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085
13086static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013087unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090}
13091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013092PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013095Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096
13097static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013098unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013100 if (PyUnicode_READY(self) == -1)
13101 return NULL;
13102 if (PyUnicode_IS_ASCII(self))
13103 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013104 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105}
13106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013107PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013110Pad a numeric string S with zeros on the left, to fill a field\n\
13111of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112
13113static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013114unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013116 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013117 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013118 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 int kind;
13120 void *data;
13121 Py_UCS4 chr;
13122
Martin v. Löwis18e16552006-02-15 17:27:45 +000013123 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 return NULL;
13125
Benjamin Petersonbac79492012-01-14 13:34:47 -050013126 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013128
Victor Stinnerc4b49542011-12-11 22:44:26 +010013129 if (PyUnicode_GET_LENGTH(self) >= width)
13130 return unicode_result_unchanged(self);
13131
13132 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133
13134 u = pad(self, fill, 0, '0');
13135
Walter Dörwald068325e2002-04-15 13:36:47 +000013136 if (u == NULL)
13137 return NULL;
13138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013139 kind = PyUnicode_KIND(u);
13140 data = PyUnicode_DATA(u);
13141 chr = PyUnicode_READ(kind, data, fill);
13142
13143 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 PyUnicode_WRITE(kind, data, 0, chr);
13146 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147 }
13148
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013149 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013150 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152
13153#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013154static PyObject *
13155unicode__decimal2ascii(PyObject *self)
13156{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013158}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159#endif
13160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013161PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013162 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013164Return True if S starts with the specified prefix, False otherwise.\n\
13165With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013166With optional end, stop comparing S at that position.\n\
13167prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
13169static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013170unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013171 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013173 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013174 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013175 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013176 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013177 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178
Jesus Ceaac451502011-04-20 17:09:23 +020013179 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013181 if (PyTuple_Check(subobj)) {
13182 Py_ssize_t i;
13183 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013184 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013185 if (substring == NULL)
13186 return NULL;
13187 result = tailmatch(self, substring, start, end, -1);
13188 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013189 if (result == -1)
13190 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 if (result) {
13192 Py_RETURN_TRUE;
13193 }
13194 }
13195 /* nothing matched */
13196 Py_RETURN_FALSE;
13197 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013199 if (substring == NULL) {
13200 if (PyErr_ExceptionMatches(PyExc_TypeError))
13201 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13202 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013203 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013204 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013205 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013207 if (result == -1)
13208 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013209 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210}
13211
13212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013213PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013216Return True if S ends with the specified suffix, False otherwise.\n\
13217With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013218With optional end, stop comparing S at that position.\n\
13219suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220
13221static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013222unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013223 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013226 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013227 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013228 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013229 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230
Jesus Ceaac451502011-04-20 17:09:23 +020013231 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013233 if (PyTuple_Check(subobj)) {
13234 Py_ssize_t i;
13235 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013236 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013238 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013240 result = tailmatch(self, substring, start, end, +1);
13241 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013242 if (result == -1)
13243 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013244 if (result) {
13245 Py_RETURN_TRUE;
13246 }
13247 }
13248 Py_RETURN_FALSE;
13249 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013250 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013251 if (substring == NULL) {
13252 if (PyErr_ExceptionMatches(PyExc_TypeError))
13253 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13254 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013256 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013257 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013258 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013259 if (result == -1)
13260 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013261 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262}
13263
Victor Stinner202fdca2012-05-07 12:47:02 +020013264Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013265_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013266{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013267 if (!writer->readonly)
13268 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13269 else {
13270 /* Copy-on-write mode: set buffer size to 0 so
13271 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13272 * next write. */
13273 writer->size = 0;
13274 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013275 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13276 writer->data = PyUnicode_DATA(writer->buffer);
13277 writer->kind = PyUnicode_KIND(writer->buffer);
13278}
13279
Victor Stinnerd3f08822012-05-29 12:57:52 +020013280void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013281_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013282{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013283 memset(writer, 0, sizeof(*writer));
13284#ifdef Py_DEBUG
13285 writer->kind = 5; /* invalid kind */
13286#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013287 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013288}
13289
Victor Stinnerd3f08822012-05-29 12:57:52 +020013290int
13291_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13292 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013293{
Victor Stinner6989ba02013-11-18 21:08:39 +010013294#ifdef MS_WINDOWS
13295 /* On Windows, overallocate by 50% is the best factor */
13296# define OVERALLOCATE_FACTOR 2
13297#else
13298 /* On Linux, overallocate by 25% is the best factor */
13299# define OVERALLOCATE_FACTOR 4
13300#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013301 Py_ssize_t newlen;
13302 PyObject *newbuffer;
13303
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304 assert(length > 0);
13305
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 if (length > PY_SSIZE_T_MAX - writer->pos) {
13307 PyErr_NoMemory();
13308 return -1;
13309 }
13310 newlen = writer->pos + length;
13311
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013312 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013313
Victor Stinnerd3f08822012-05-29 12:57:52 +020013314 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013315 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013316 if (writer->overallocate
13317 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13318 /* overallocate to limit the number of realloc() */
13319 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013320 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013321 if (newlen < writer->min_length)
13322 newlen = writer->min_length;
13323
Victor Stinnerd3f08822012-05-29 12:57:52 +020013324 writer->buffer = PyUnicode_New(newlen, maxchar);
13325 if (writer->buffer == NULL)
13326 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013328 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013329 if (writer->overallocate
13330 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13331 /* overallocate to limit the number of realloc() */
13332 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013333 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013334 if (newlen < writer->min_length)
13335 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013336
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013337 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013338 /* resize + widen */
13339 newbuffer = PyUnicode_New(newlen, maxchar);
13340 if (newbuffer == NULL)
13341 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013342 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13343 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013344 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013345 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013346 }
13347 else {
13348 newbuffer = resize_compact(writer->buffer, newlen);
13349 if (newbuffer == NULL)
13350 return -1;
13351 }
13352 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013353 }
13354 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013355 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013356 newbuffer = PyUnicode_New(writer->size, maxchar);
13357 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013358 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013359 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13360 writer->buffer, 0, writer->pos);
13361 Py_DECREF(writer->buffer);
13362 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013363 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013364 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013365 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013366
13367#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013368}
13369
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013370Py_LOCAL_INLINE(int)
13371_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013372{
13373 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13374 return -1;
13375 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13376 writer->pos++;
13377 return 0;
13378}
13379
13380int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013381_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13382{
13383 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13384}
13385
13386int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013387_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13388{
13389 Py_UCS4 maxchar;
13390 Py_ssize_t len;
13391
13392 if (PyUnicode_READY(str) == -1)
13393 return -1;
13394 len = PyUnicode_GET_LENGTH(str);
13395 if (len == 0)
13396 return 0;
13397 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13398 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013399 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013400 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013401 Py_INCREF(str);
13402 writer->buffer = str;
13403 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013404 writer->pos += len;
13405 return 0;
13406 }
13407 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13408 return -1;
13409 }
13410 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13411 str, 0, len);
13412 writer->pos += len;
13413 return 0;
13414}
13415
Victor Stinnere215d962012-10-06 23:03:36 +020013416int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013417_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13418 Py_ssize_t start, Py_ssize_t end)
13419{
13420 Py_UCS4 maxchar;
13421 Py_ssize_t len;
13422
13423 if (PyUnicode_READY(str) == -1)
13424 return -1;
13425
13426 assert(0 <= start);
13427 assert(end <= PyUnicode_GET_LENGTH(str));
13428 assert(start <= end);
13429
13430 if (end == 0)
13431 return 0;
13432
13433 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13434 return _PyUnicodeWriter_WriteStr(writer, str);
13435
13436 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13437 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13438 else
13439 maxchar = writer->maxchar;
13440 len = end - start;
13441
13442 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13443 return -1;
13444
13445 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13446 str, start, len);
13447 writer->pos += len;
13448 return 0;
13449}
13450
13451int
Victor Stinner4a587072013-11-19 12:54:53 +010013452_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13453 const char *ascii, Py_ssize_t len)
13454{
13455 if (len == -1)
13456 len = strlen(ascii);
13457
13458 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13459
13460 if (writer->buffer == NULL && !writer->overallocate) {
13461 PyObject *str;
13462
13463 str = _PyUnicode_FromASCII(ascii, len);
13464 if (str == NULL)
13465 return -1;
13466
13467 writer->readonly = 1;
13468 writer->buffer = str;
13469 _PyUnicodeWriter_Update(writer);
13470 writer->pos += len;
13471 return 0;
13472 }
13473
13474 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13475 return -1;
13476
13477 switch (writer->kind)
13478 {
13479 case PyUnicode_1BYTE_KIND:
13480 {
13481 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13482 Py_UCS1 *data = writer->data;
13483
13484 Py_MEMCPY(data + writer->pos, str, len);
13485 break;
13486 }
13487 case PyUnicode_2BYTE_KIND:
13488 {
13489 _PyUnicode_CONVERT_BYTES(
13490 Py_UCS1, Py_UCS2,
13491 ascii, ascii + len,
13492 (Py_UCS2 *)writer->data + writer->pos);
13493 break;
13494 }
13495 case PyUnicode_4BYTE_KIND:
13496 {
13497 _PyUnicode_CONVERT_BYTES(
13498 Py_UCS1, Py_UCS4,
13499 ascii, ascii + len,
13500 (Py_UCS4 *)writer->data + writer->pos);
13501 break;
13502 }
13503 default:
13504 assert(0);
13505 }
13506
13507 writer->pos += len;
13508 return 0;
13509}
13510
13511int
13512_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13513 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013514{
13515 Py_UCS4 maxchar;
13516
13517 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13518 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13519 return -1;
13520 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13521 writer->pos += len;
13522 return 0;
13523}
13524
Victor Stinnerd3f08822012-05-29 12:57:52 +020013525PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013526_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013527{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013528 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013529 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013530 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013531 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013532 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013533 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013534 str = writer->buffer;
13535 writer->buffer = NULL;
13536 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13537 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013538 }
13539 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13540 PyObject *newbuffer;
13541 newbuffer = resize_compact(writer->buffer, writer->pos);
13542 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013543 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544 return NULL;
13545 }
13546 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013547 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013548 str = writer->buffer;
13549 writer->buffer = NULL;
13550 assert(_PyUnicode_CheckConsistency(str, 1));
13551 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013552}
13553
Victor Stinnerd3f08822012-05-29 12:57:52 +020013554void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013555_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013556{
13557 Py_CLEAR(writer->buffer);
13558}
13559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013560#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013561
13562PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013564\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013565Return a formatted version of S, using substitutions from args and kwargs.\n\
13566The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013567
Eric Smith27bbca62010-11-04 17:06:58 +000013568PyDoc_STRVAR(format_map__doc__,
13569 "S.format_map(mapping) -> str\n\
13570\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013571Return a formatted version of S, using substitutions from mapping.\n\
13572The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013573
Eric Smith4a7d76d2008-05-30 18:10:19 +000013574static PyObject *
13575unicode__format__(PyObject* self, PyObject* args)
13576{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013577 PyObject *format_spec;
13578 _PyUnicodeWriter writer;
13579 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013580
13581 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13582 return NULL;
13583
Victor Stinnerd3f08822012-05-29 12:57:52 +020013584 if (PyUnicode_READY(self) == -1)
13585 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013586 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013587 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13588 self, format_spec, 0,
13589 PyUnicode_GET_LENGTH(format_spec));
13590 if (ret == -1) {
13591 _PyUnicodeWriter_Dealloc(&writer);
13592 return NULL;
13593 }
13594 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013595}
13596
Eric Smith8c663262007-08-25 02:26:07 +000013597PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013599\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013600Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013601
13602static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013603unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013604{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013605 Py_ssize_t size;
13606
13607 /* If it's a compact object, account for base structure +
13608 character data. */
13609 if (PyUnicode_IS_COMPACT_ASCII(v))
13610 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13611 else if (PyUnicode_IS_COMPACT(v))
13612 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013613 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013614 else {
13615 /* If it is a two-block object, account for base object, and
13616 for character block if present. */
13617 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013618 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013619 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013620 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013621 }
13622 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013623 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013624 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013625 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013626 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013627 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013628
13629 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013630}
13631
13632PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013634
13635static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013636unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013637{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013638 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013639 if (!copy)
13640 return NULL;
13641 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013642}
13643
Guido van Rossumd57fd912000-03-10 22:53:23 +000013644static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013645 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013646 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013647 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13648 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013649 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13650 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013651 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013652 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13653 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13654 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013655 {"expandtabs", (PyCFunction) unicode_expandtabs,
13656 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013657 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013658 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013659 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13660 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13661 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013662 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013663 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13664 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13665 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013666 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013667 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013668 {"splitlines", (PyCFunction) unicode_splitlines,
13669 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013670 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013671 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13672 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13673 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13674 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13675 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13676 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13677 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13678 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13679 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13680 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13681 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13682 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13683 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13684 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013685 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013686 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013687 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013688 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013689 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013690 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013691 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013692 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013693#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013694 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013695 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013696#endif
13697
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013699 {NULL, NULL}
13700};
13701
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013702static PyObject *
13703unicode_mod(PyObject *v, PyObject *w)
13704{
Brian Curtindfc80e32011-08-10 20:28:54 -050013705 if (!PyUnicode_Check(v))
13706 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013707 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013708}
13709
13710static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013711 0, /*nb_add*/
13712 0, /*nb_subtract*/
13713 0, /*nb_multiply*/
13714 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013715};
13716
Guido van Rossumd57fd912000-03-10 22:53:23 +000013717static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013718 (lenfunc) unicode_length, /* sq_length */
13719 PyUnicode_Concat, /* sq_concat */
13720 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13721 (ssizeargfunc) unicode_getitem, /* sq_item */
13722 0, /* sq_slice */
13723 0, /* sq_ass_item */
13724 0, /* sq_ass_slice */
13725 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013726};
13727
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013728static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013729unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013730{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013731 if (PyUnicode_READY(self) == -1)
13732 return NULL;
13733
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013734 if (PyIndex_Check(item)) {
13735 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013736 if (i == -1 && PyErr_Occurred())
13737 return NULL;
13738 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013739 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013740 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013741 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013742 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013743 PyObject *result;
13744 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013745 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013746 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013748 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013750 return NULL;
13751 }
13752
13753 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013754 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013755 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013756 slicelength == PyUnicode_GET_LENGTH(self)) {
13757 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013758 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013759 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013760 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013761 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013762 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013763 src_kind = PyUnicode_KIND(self);
13764 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013765 if (!PyUnicode_IS_ASCII(self)) {
13766 kind_limit = kind_maxchar_limit(src_kind);
13767 max_char = 0;
13768 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13769 ch = PyUnicode_READ(src_kind, src_data, cur);
13770 if (ch > max_char) {
13771 max_char = ch;
13772 if (max_char >= kind_limit)
13773 break;
13774 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013775 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013776 }
Victor Stinner55c99112011-10-13 01:17:06 +020013777 else
13778 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013779 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013780 if (result == NULL)
13781 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013782 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013783 dest_data = PyUnicode_DATA(result);
13784
13785 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013786 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13787 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013788 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013789 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013790 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013791 } else {
13792 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13793 return NULL;
13794 }
13795}
13796
13797static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013798 (lenfunc)unicode_length, /* mp_length */
13799 (binaryfunc)unicode_subscript, /* mp_subscript */
13800 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013801};
13802
Guido van Rossumd57fd912000-03-10 22:53:23 +000013803
Guido van Rossumd57fd912000-03-10 22:53:23 +000013804/* Helpers for PyUnicode_Format() */
13805
Victor Stinnera47082312012-10-04 02:19:54 +020013806struct unicode_formatter_t {
13807 PyObject *args;
13808 int args_owned;
13809 Py_ssize_t arglen, argidx;
13810 PyObject *dict;
13811
13812 enum PyUnicode_Kind fmtkind;
13813 Py_ssize_t fmtcnt, fmtpos;
13814 void *fmtdata;
13815 PyObject *fmtstr;
13816
13817 _PyUnicodeWriter writer;
13818};
13819
13820struct unicode_format_arg_t {
13821 Py_UCS4 ch;
13822 int flags;
13823 Py_ssize_t width;
13824 int prec;
13825 int sign;
13826};
13827
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013829unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830{
Victor Stinnera47082312012-10-04 02:19:54 +020013831 Py_ssize_t argidx = ctx->argidx;
13832
13833 if (argidx < ctx->arglen) {
13834 ctx->argidx++;
13835 if (ctx->arglen < 0)
13836 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else
Victor Stinnera47082312012-10-04 02:19:54 +020013838 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013839 }
13840 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013841 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013842 return NULL;
13843}
13844
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013845/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013846
Victor Stinnera47082312012-10-04 02:19:54 +020013847/* Format a float into the writer if the writer is not NULL, or into *p_output
13848 otherwise.
13849
13850 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013851static int
Victor Stinnera47082312012-10-04 02:19:54 +020013852formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13853 PyObject **p_output,
13854 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013855{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013856 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013857 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013858 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013859 int prec;
13860 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013861
Guido van Rossumd57fd912000-03-10 22:53:23 +000013862 x = PyFloat_AsDouble(v);
13863 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013864 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013865
Victor Stinnera47082312012-10-04 02:19:54 +020013866 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013867 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013869
Victor Stinnera47082312012-10-04 02:19:54 +020013870 if (arg->flags & F_ALT)
13871 dtoa_flags = Py_DTSF_ALT;
13872 else
13873 dtoa_flags = 0;
13874 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013875 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013876 return -1;
13877 len = strlen(p);
13878 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013879 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013880 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013881 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013882 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013883 }
13884 else
13885 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013886 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013887 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888}
13889
Victor Stinnerd0880d52012-04-27 23:40:13 +020013890/* formatlong() emulates the format codes d, u, o, x and X, and
13891 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13892 * Python's regular ints.
13893 * Return value: a new PyUnicodeObject*, or NULL if error.
13894 * The output string is of the form
13895 * "-"? ("0x" | "0X")? digit+
13896 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13897 * set in flags. The case of hex digits will be correct,
13898 * There will be at least prec digits, zero-filled on the left if
13899 * necessary to get that many.
13900 * val object to be converted
13901 * flags bitmask of format flags; only F_ALT is looked at
13902 * prec minimum number of digits; 0-fill on left if needed
13903 * type a character in [duoxX]; u acts the same as d
13904 *
13905 * CAUTION: o, x and X conversions on regular ints can never
13906 * produce a '-' sign, but can for Python's unbounded ints.
13907 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013908static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013909formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013910{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013911 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013912 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013913 Py_ssize_t i;
13914 int sign; /* 1 if '-', else 0 */
13915 int len; /* number of characters */
13916 Py_ssize_t llen;
13917 int numdigits; /* len == numnondigits + numdigits */
13918 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013919 int prec = arg->prec;
13920 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013921
Victor Stinnerd0880d52012-04-27 23:40:13 +020013922 /* Avoid exceeding SSIZE_T_MAX */
13923 if (prec > INT_MAX-3) {
13924 PyErr_SetString(PyExc_OverflowError,
13925 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013926 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013927 }
13928
13929 assert(PyLong_Check(val));
13930
13931 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013932 default:
13933 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013934 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013935 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013936 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013937 /* int and int subclasses should print numerically when a numeric */
13938 /* format code is used (see issue18780) */
13939 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013940 break;
13941 case 'o':
13942 numnondigits = 2;
13943 result = PyNumber_ToBase(val, 8);
13944 break;
13945 case 'x':
13946 case 'X':
13947 numnondigits = 2;
13948 result = PyNumber_ToBase(val, 16);
13949 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013950 }
13951 if (!result)
13952 return NULL;
13953
13954 assert(unicode_modifiable(result));
13955 assert(PyUnicode_IS_READY(result));
13956 assert(PyUnicode_IS_ASCII(result));
13957
13958 /* To modify the string in-place, there can only be one reference. */
13959 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013960 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013961 PyErr_BadInternalCall();
13962 return NULL;
13963 }
13964 buf = PyUnicode_DATA(result);
13965 llen = PyUnicode_GET_LENGTH(result);
13966 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013967 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013968 PyErr_SetString(PyExc_ValueError,
13969 "string too large in _PyBytes_FormatLong");
13970 return NULL;
13971 }
13972 len = (int)llen;
13973 sign = buf[0] == '-';
13974 numnondigits += sign;
13975 numdigits = len - numnondigits;
13976 assert(numdigits > 0);
13977
13978 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013979 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013980 (type == 'o' || type == 'x' || type == 'X'))) {
13981 assert(buf[sign] == '0');
13982 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13983 buf[sign+1] == 'o');
13984 numnondigits -= 2;
13985 buf += 2;
13986 len -= 2;
13987 if (sign)
13988 buf[0] = '-';
13989 assert(len == numnondigits + numdigits);
13990 assert(numdigits > 0);
13991 }
13992
13993 /* Fill with leading zeroes to meet minimum width. */
13994 if (prec > numdigits) {
13995 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13996 numnondigits + prec);
13997 char *b1;
13998 if (!r1) {
13999 Py_DECREF(result);
14000 return NULL;
14001 }
14002 b1 = PyBytes_AS_STRING(r1);
14003 for (i = 0; i < numnondigits; ++i)
14004 *b1++ = *buf++;
14005 for (i = 0; i < prec - numdigits; i++)
14006 *b1++ = '0';
14007 for (i = 0; i < numdigits; i++)
14008 *b1++ = *buf++;
14009 *b1 = '\0';
14010 Py_DECREF(result);
14011 result = r1;
14012 buf = PyBytes_AS_STRING(result);
14013 len = numnondigits + prec;
14014 }
14015
14016 /* Fix up case for hex conversions. */
14017 if (type == 'X') {
14018 /* Need to convert all lower case letters to upper case.
14019 and need to convert 0x to 0X (and -0x to -0X). */
14020 for (i = 0; i < len; i++)
14021 if (buf[i] >= 'a' && buf[i] <= 'x')
14022 buf[i] -= 'a'-'A';
14023 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014024 if (!PyUnicode_Check(result)
14025 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014026 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014027 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014028 Py_DECREF(result);
14029 result = unicode;
14030 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014031 else if (len != PyUnicode_GET_LENGTH(result)) {
14032 if (PyUnicode_Resize(&result, len) < 0)
14033 Py_CLEAR(result);
14034 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014036}
14037
Ethan Furmandf3ed242014-01-05 06:50:30 -080014038/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014039 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014040 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014041 * -1 and raise an exception on error */
14042static int
Victor Stinnera47082312012-10-04 02:19:54 +020014043mainformatlong(PyObject *v,
14044 struct unicode_format_arg_t *arg,
14045 PyObject **p_output,
14046 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014047{
14048 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014049 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014050
14051 if (!PyNumber_Check(v))
14052 goto wrongtype;
14053
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014054 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014055 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014056 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014057 if (type == 'o' || type == 'x' || type == 'X') {
14058 iobj = PyNumber_Index(v);
14059 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014060 PyErr_Clear();
14061 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14062 "automatic int conversions have been deprecated",
14063 1)) {
14064 return -1;
14065 }
14066 iobj = PyNumber_Long(v);
14067 if (iobj == NULL ) {
14068 if (PyErr_ExceptionMatches(PyExc_TypeError))
14069 goto wrongtype;
14070 return -1;
14071 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014072 }
14073 }
14074 else {
14075 iobj = PyNumber_Long(v);
14076 if (iobj == NULL ) {
14077 if (PyErr_ExceptionMatches(PyExc_TypeError))
14078 goto wrongtype;
14079 return -1;
14080 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014081 }
14082 assert(PyLong_Check(iobj));
14083 }
14084 else {
14085 iobj = v;
14086 Py_INCREF(iobj);
14087 }
14088
14089 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014090 && arg->width == -1 && arg->prec == -1
14091 && !(arg->flags & (F_SIGN | F_BLANK))
14092 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014093 {
14094 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014095 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014096 int base;
14097
Victor Stinnera47082312012-10-04 02:19:54 +020014098 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014099 {
14100 default:
14101 assert(0 && "'type' not in [diuoxX]");
14102 case 'd':
14103 case 'i':
14104 case 'u':
14105 base = 10;
14106 break;
14107 case 'o':
14108 base = 8;
14109 break;
14110 case 'x':
14111 case 'X':
14112 base = 16;
14113 break;
14114 }
14115
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014116 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14117 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014118 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014119 }
14120 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014121 return 1;
14122 }
14123
Victor Stinnera47082312012-10-04 02:19:54 +020014124 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014125 Py_DECREF(iobj);
14126 if (res == NULL)
14127 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014128 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014129 return 0;
14130
14131wrongtype:
14132 PyErr_Format(PyExc_TypeError,
14133 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014134 "not %.200s",
14135 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014136 return -1;
14137}
14138
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014139static Py_UCS4
14140formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014141{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014142 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014143 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014144 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014145 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014146 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014147 goto onError;
14148 }
14149 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014150 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014151 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014152 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014153 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014154 if (!PyLong_Check(v)) {
14155 iobj = PyNumber_Index(v);
14156 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014157 PyErr_Clear();
14158 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14159 "automatic int conversions have been deprecated",
14160 1)) {
14161 return -1;
14162 }
14163 iobj = PyNumber_Long(v);
14164 if (iobj == NULL ) {
14165 if (PyErr_ExceptionMatches(PyExc_TypeError))
14166 goto onError;
14167 return -1;
14168 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014169 }
14170 v = iobj;
14171 Py_DECREF(iobj);
14172 }
14173 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014174 x = PyLong_AsLong(v);
14175 if (x == -1 && PyErr_Occurred())
14176 goto onError;
14177
Victor Stinner8faf8212011-12-08 22:14:11 +010014178 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014179 PyErr_SetString(PyExc_OverflowError,
14180 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014181 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014182 }
14183
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014184 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014185 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014186
Benjamin Peterson29060642009-01-31 22:14:21 +000014187 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014188 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014189 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014190 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014191}
14192
Victor Stinnera47082312012-10-04 02:19:54 +020014193/* Parse options of an argument: flags, width, precision.
14194 Handle also "%(name)" syntax.
14195
14196 Return 0 if the argument has been formatted into arg->str.
14197 Return 1 if the argument has been written into ctx->writer,
14198 Raise an exception and return -1 on error. */
14199static int
14200unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14201 struct unicode_format_arg_t *arg)
14202{
14203#define FORMAT_READ(ctx) \
14204 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14205
14206 PyObject *v;
14207
Victor Stinnera47082312012-10-04 02:19:54 +020014208 if (arg->ch == '(') {
14209 /* Get argument value from a dictionary. Example: "%(name)s". */
14210 Py_ssize_t keystart;
14211 Py_ssize_t keylen;
14212 PyObject *key;
14213 int pcount = 1;
14214
14215 if (ctx->dict == NULL) {
14216 PyErr_SetString(PyExc_TypeError,
14217 "format requires a mapping");
14218 return -1;
14219 }
14220 ++ctx->fmtpos;
14221 --ctx->fmtcnt;
14222 keystart = ctx->fmtpos;
14223 /* Skip over balanced parentheses */
14224 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14225 arg->ch = FORMAT_READ(ctx);
14226 if (arg->ch == ')')
14227 --pcount;
14228 else if (arg->ch == '(')
14229 ++pcount;
14230 ctx->fmtpos++;
14231 }
14232 keylen = ctx->fmtpos - keystart - 1;
14233 if (ctx->fmtcnt < 0 || pcount > 0) {
14234 PyErr_SetString(PyExc_ValueError,
14235 "incomplete format key");
14236 return -1;
14237 }
14238 key = PyUnicode_Substring(ctx->fmtstr,
14239 keystart, keystart + keylen);
14240 if (key == NULL)
14241 return -1;
14242 if (ctx->args_owned) {
14243 Py_DECREF(ctx->args);
14244 ctx->args_owned = 0;
14245 }
14246 ctx->args = PyObject_GetItem(ctx->dict, key);
14247 Py_DECREF(key);
14248 if (ctx->args == NULL)
14249 return -1;
14250 ctx->args_owned = 1;
14251 ctx->arglen = -1;
14252 ctx->argidx = -2;
14253 }
14254
14255 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014256 while (--ctx->fmtcnt >= 0) {
14257 arg->ch = FORMAT_READ(ctx);
14258 ctx->fmtpos++;
14259 switch (arg->ch) {
14260 case '-': arg->flags |= F_LJUST; continue;
14261 case '+': arg->flags |= F_SIGN; continue;
14262 case ' ': arg->flags |= F_BLANK; continue;
14263 case '#': arg->flags |= F_ALT; continue;
14264 case '0': arg->flags |= F_ZERO; continue;
14265 }
14266 break;
14267 }
14268
14269 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014270 if (arg->ch == '*') {
14271 v = unicode_format_getnextarg(ctx);
14272 if (v == NULL)
14273 return -1;
14274 if (!PyLong_Check(v)) {
14275 PyErr_SetString(PyExc_TypeError,
14276 "* wants int");
14277 return -1;
14278 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014279 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014280 if (arg->width == -1 && PyErr_Occurred())
14281 return -1;
14282 if (arg->width < 0) {
14283 arg->flags |= F_LJUST;
14284 arg->width = -arg->width;
14285 }
14286 if (--ctx->fmtcnt >= 0) {
14287 arg->ch = FORMAT_READ(ctx);
14288 ctx->fmtpos++;
14289 }
14290 }
14291 else if (arg->ch >= '0' && arg->ch <= '9') {
14292 arg->width = arg->ch - '0';
14293 while (--ctx->fmtcnt >= 0) {
14294 arg->ch = FORMAT_READ(ctx);
14295 ctx->fmtpos++;
14296 if (arg->ch < '0' || arg->ch > '9')
14297 break;
14298 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14299 mixing signed and unsigned comparison. Since arg->ch is between
14300 '0' and '9', casting to int is safe. */
14301 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14302 PyErr_SetString(PyExc_ValueError,
14303 "width too big");
14304 return -1;
14305 }
14306 arg->width = arg->width*10 + (arg->ch - '0');
14307 }
14308 }
14309
14310 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014311 if (arg->ch == '.') {
14312 arg->prec = 0;
14313 if (--ctx->fmtcnt >= 0) {
14314 arg->ch = FORMAT_READ(ctx);
14315 ctx->fmtpos++;
14316 }
14317 if (arg->ch == '*') {
14318 v = unicode_format_getnextarg(ctx);
14319 if (v == NULL)
14320 return -1;
14321 if (!PyLong_Check(v)) {
14322 PyErr_SetString(PyExc_TypeError,
14323 "* wants int");
14324 return -1;
14325 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014326 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014327 if (arg->prec == -1 && PyErr_Occurred())
14328 return -1;
14329 if (arg->prec < 0)
14330 arg->prec = 0;
14331 if (--ctx->fmtcnt >= 0) {
14332 arg->ch = FORMAT_READ(ctx);
14333 ctx->fmtpos++;
14334 }
14335 }
14336 else if (arg->ch >= '0' && arg->ch <= '9') {
14337 arg->prec = arg->ch - '0';
14338 while (--ctx->fmtcnt >= 0) {
14339 arg->ch = FORMAT_READ(ctx);
14340 ctx->fmtpos++;
14341 if (arg->ch < '0' || arg->ch > '9')
14342 break;
14343 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14344 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014345 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014346 return -1;
14347 }
14348 arg->prec = arg->prec*10 + (arg->ch - '0');
14349 }
14350 }
14351 }
14352
14353 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14354 if (ctx->fmtcnt >= 0) {
14355 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14356 if (--ctx->fmtcnt >= 0) {
14357 arg->ch = FORMAT_READ(ctx);
14358 ctx->fmtpos++;
14359 }
14360 }
14361 }
14362 if (ctx->fmtcnt < 0) {
14363 PyErr_SetString(PyExc_ValueError,
14364 "incomplete format");
14365 return -1;
14366 }
14367 return 0;
14368
14369#undef FORMAT_READ
14370}
14371
14372/* Format one argument. Supported conversion specifiers:
14373
14374 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014375 - "i", "d", "u": int or float
14376 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014377 - "e", "E", "f", "F", "g", "G": float
14378 - "c": int or str (1 character)
14379
Victor Stinner8dbd4212012-12-04 09:30:24 +010014380 When possible, the output is written directly into the Unicode writer
14381 (ctx->writer). A string is created when padding is required.
14382
Victor Stinnera47082312012-10-04 02:19:54 +020014383 Return 0 if the argument has been formatted into *p_str,
14384 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014385 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014386static int
14387unicode_format_arg_format(struct unicode_formatter_t *ctx,
14388 struct unicode_format_arg_t *arg,
14389 PyObject **p_str)
14390{
14391 PyObject *v;
14392 _PyUnicodeWriter *writer = &ctx->writer;
14393
14394 if (ctx->fmtcnt == 0)
14395 ctx->writer.overallocate = 0;
14396
14397 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014398 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014399 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014400 return 1;
14401 }
14402
14403 v = unicode_format_getnextarg(ctx);
14404 if (v == NULL)
14405 return -1;
14406
Victor Stinnera47082312012-10-04 02:19:54 +020014407
14408 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014409 case 's':
14410 case 'r':
14411 case 'a':
14412 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14413 /* Fast path */
14414 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14415 return -1;
14416 return 1;
14417 }
14418
14419 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14420 *p_str = v;
14421 Py_INCREF(*p_str);
14422 }
14423 else {
14424 if (arg->ch == 's')
14425 *p_str = PyObject_Str(v);
14426 else if (arg->ch == 'r')
14427 *p_str = PyObject_Repr(v);
14428 else
14429 *p_str = PyObject_ASCII(v);
14430 }
14431 break;
14432
14433 case 'i':
14434 case 'd':
14435 case 'u':
14436 case 'o':
14437 case 'x':
14438 case 'X':
14439 {
14440 int ret = mainformatlong(v, arg, p_str, writer);
14441 if (ret != 0)
14442 return ret;
14443 arg->sign = 1;
14444 break;
14445 }
14446
14447 case 'e':
14448 case 'E':
14449 case 'f':
14450 case 'F':
14451 case 'g':
14452 case 'G':
14453 if (arg->width == -1 && arg->prec == -1
14454 && !(arg->flags & (F_SIGN | F_BLANK)))
14455 {
14456 /* Fast path */
14457 if (formatfloat(v, arg, NULL, writer) == -1)
14458 return -1;
14459 return 1;
14460 }
14461
14462 arg->sign = 1;
14463 if (formatfloat(v, arg, p_str, NULL) == -1)
14464 return -1;
14465 break;
14466
14467 case 'c':
14468 {
14469 Py_UCS4 ch = formatchar(v);
14470 if (ch == (Py_UCS4) -1)
14471 return -1;
14472 if (arg->width == -1 && arg->prec == -1) {
14473 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014474 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014475 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014476 return 1;
14477 }
14478 *p_str = PyUnicode_FromOrdinal(ch);
14479 break;
14480 }
14481
14482 default:
14483 PyErr_Format(PyExc_ValueError,
14484 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014485 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014486 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14487 (int)arg->ch,
14488 ctx->fmtpos - 1);
14489 return -1;
14490 }
14491 if (*p_str == NULL)
14492 return -1;
14493 assert (PyUnicode_Check(*p_str));
14494 return 0;
14495}
14496
14497static int
14498unicode_format_arg_output(struct unicode_formatter_t *ctx,
14499 struct unicode_format_arg_t *arg,
14500 PyObject *str)
14501{
14502 Py_ssize_t len;
14503 enum PyUnicode_Kind kind;
14504 void *pbuf;
14505 Py_ssize_t pindex;
14506 Py_UCS4 signchar;
14507 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014508 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014509 Py_ssize_t sublen;
14510 _PyUnicodeWriter *writer = &ctx->writer;
14511 Py_UCS4 fill;
14512
14513 fill = ' ';
14514 if (arg->sign && arg->flags & F_ZERO)
14515 fill = '0';
14516
14517 if (PyUnicode_READY(str) == -1)
14518 return -1;
14519
14520 len = PyUnicode_GET_LENGTH(str);
14521 if ((arg->width == -1 || arg->width <= len)
14522 && (arg->prec == -1 || arg->prec >= len)
14523 && !(arg->flags & (F_SIGN | F_BLANK)))
14524 {
14525 /* Fast path */
14526 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14527 return -1;
14528 return 0;
14529 }
14530
14531 /* Truncate the string for "s", "r" and "a" formats
14532 if the precision is set */
14533 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14534 if (arg->prec >= 0 && len > arg->prec)
14535 len = arg->prec;
14536 }
14537
14538 /* Adjust sign and width */
14539 kind = PyUnicode_KIND(str);
14540 pbuf = PyUnicode_DATA(str);
14541 pindex = 0;
14542 signchar = '\0';
14543 if (arg->sign) {
14544 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14545 if (ch == '-' || ch == '+') {
14546 signchar = ch;
14547 len--;
14548 pindex++;
14549 }
14550 else if (arg->flags & F_SIGN)
14551 signchar = '+';
14552 else if (arg->flags & F_BLANK)
14553 signchar = ' ';
14554 else
14555 arg->sign = 0;
14556 }
14557 if (arg->width < len)
14558 arg->width = len;
14559
14560 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014561 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014562 if (!(arg->flags & F_LJUST)) {
14563 if (arg->sign) {
14564 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014565 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014566 }
14567 else {
14568 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014569 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014570 }
14571 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014572 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14573 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014574 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014575 }
14576
Victor Stinnera47082312012-10-04 02:19:54 +020014577 buflen = arg->width;
14578 if (arg->sign && len == arg->width)
14579 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014580 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014581 return -1;
14582
14583 /* Write the sign if needed */
14584 if (arg->sign) {
14585 if (fill != ' ') {
14586 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14587 writer->pos += 1;
14588 }
14589 if (arg->width > len)
14590 arg->width--;
14591 }
14592
14593 /* Write the numeric prefix for "x", "X" and "o" formats
14594 if the alternate form is used.
14595 For example, write "0x" for the "%#x" format. */
14596 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14597 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14598 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14599 if (fill != ' ') {
14600 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14601 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14602 writer->pos += 2;
14603 pindex += 2;
14604 }
14605 arg->width -= 2;
14606 if (arg->width < 0)
14607 arg->width = 0;
14608 len -= 2;
14609 }
14610
14611 /* Pad left with the fill character if needed */
14612 if (arg->width > len && !(arg->flags & F_LJUST)) {
14613 sublen = arg->width - len;
14614 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14615 writer->pos += sublen;
14616 arg->width = len;
14617 }
14618
14619 /* If padding with spaces: write sign if needed and/or numeric prefix if
14620 the alternate form is used */
14621 if (fill == ' ') {
14622 if (arg->sign) {
14623 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14624 writer->pos += 1;
14625 }
14626 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14627 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14628 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14629 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14630 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14631 writer->pos += 2;
14632 pindex += 2;
14633 }
14634 }
14635
14636 /* Write characters */
14637 if (len) {
14638 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14639 str, pindex, len);
14640 writer->pos += len;
14641 }
14642
14643 /* Pad right with the fill character if needed */
14644 if (arg->width > len) {
14645 sublen = arg->width - len;
14646 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14647 writer->pos += sublen;
14648 }
14649 return 0;
14650}
14651
14652/* Helper of PyUnicode_Format(): format one arg.
14653 Return 0 on success, raise an exception and return -1 on error. */
14654static int
14655unicode_format_arg(struct unicode_formatter_t *ctx)
14656{
14657 struct unicode_format_arg_t arg;
14658 PyObject *str;
14659 int ret;
14660
Victor Stinner8dbd4212012-12-04 09:30:24 +010014661 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14662 arg.flags = 0;
14663 arg.width = -1;
14664 arg.prec = -1;
14665 arg.sign = 0;
14666 str = NULL;
14667
Victor Stinnera47082312012-10-04 02:19:54 +020014668 ret = unicode_format_arg_parse(ctx, &arg);
14669 if (ret == -1)
14670 return -1;
14671
14672 ret = unicode_format_arg_format(ctx, &arg, &str);
14673 if (ret == -1)
14674 return -1;
14675
14676 if (ret != 1) {
14677 ret = unicode_format_arg_output(ctx, &arg, str);
14678 Py_DECREF(str);
14679 if (ret == -1)
14680 return -1;
14681 }
14682
14683 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14684 PyErr_SetString(PyExc_TypeError,
14685 "not all arguments converted during string formatting");
14686 return -1;
14687 }
14688 return 0;
14689}
14690
Alexander Belopolsky40018472011-02-26 01:02:56 +000014691PyObject *
14692PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014693{
Victor Stinnera47082312012-10-04 02:19:54 +020014694 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014695
Guido van Rossumd57fd912000-03-10 22:53:23 +000014696 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014697 PyErr_BadInternalCall();
14698 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014699 }
Victor Stinnera47082312012-10-04 02:19:54 +020014700
14701 ctx.fmtstr = PyUnicode_FromObject(format);
14702 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014703 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014704 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14705 Py_DECREF(ctx.fmtstr);
14706 return NULL;
14707 }
14708 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14709 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14710 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14711 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014712
Victor Stinner8f674cc2013-04-17 23:02:17 +020014713 _PyUnicodeWriter_Init(&ctx.writer);
14714 ctx.writer.min_length = ctx.fmtcnt + 100;
14715 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014716
Guido van Rossumd57fd912000-03-10 22:53:23 +000014717 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014718 ctx.arglen = PyTuple_Size(args);
14719 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014720 }
14721 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014722 ctx.arglen = -1;
14723 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014724 }
Victor Stinnera47082312012-10-04 02:19:54 +020014725 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014726 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014727 ctx.dict = args;
14728 else
14729 ctx.dict = NULL;
14730 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014731
Victor Stinnera47082312012-10-04 02:19:54 +020014732 while (--ctx.fmtcnt >= 0) {
14733 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014734 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014735
14736 nonfmtpos = ctx.fmtpos++;
14737 while (ctx.fmtcnt >= 0 &&
14738 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14739 ctx.fmtpos++;
14740 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014741 }
Victor Stinnera47082312012-10-04 02:19:54 +020014742 if (ctx.fmtcnt < 0) {
14743 ctx.fmtpos--;
14744 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014745 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014746
Victor Stinnercfc4c132013-04-03 01:48:39 +020014747 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14748 nonfmtpos, ctx.fmtpos) < 0)
14749 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014750 }
14751 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014752 ctx.fmtpos++;
14753 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014754 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014755 }
14756 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014757
Victor Stinnera47082312012-10-04 02:19:54 +020014758 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014759 PyErr_SetString(PyExc_TypeError,
14760 "not all arguments converted during string formatting");
14761 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014762 }
14763
Victor Stinnera47082312012-10-04 02:19:54 +020014764 if (ctx.args_owned) {
14765 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014766 }
Victor Stinnera47082312012-10-04 02:19:54 +020014767 Py_DECREF(ctx.fmtstr);
14768 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014769
Benjamin Peterson29060642009-01-31 22:14:21 +000014770 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014771 Py_DECREF(ctx.fmtstr);
14772 _PyUnicodeWriter_Dealloc(&ctx.writer);
14773 if (ctx.args_owned) {
14774 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014775 }
14776 return NULL;
14777}
14778
Jeremy Hylton938ace62002-07-17 16:30:39 +000014779static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014780unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14781
Tim Peters6d6c1a32001-08-02 04:15:00 +000014782static PyObject *
14783unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14784{
Benjamin Peterson29060642009-01-31 22:14:21 +000014785 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014786 static char *kwlist[] = {"object", "encoding", "errors", 0};
14787 char *encoding = NULL;
14788 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014789
Benjamin Peterson14339b62009-01-31 16:36:08 +000014790 if (type != &PyUnicode_Type)
14791 return unicode_subtype_new(type, args, kwds);
14792 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014793 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014794 return NULL;
14795 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014796 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014797 if (encoding == NULL && errors == NULL)
14798 return PyObject_Str(x);
14799 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014800 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014801}
14802
Guido van Rossume023fe02001-08-30 03:12:59 +000014803static PyObject *
14804unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14805{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014806 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014807 Py_ssize_t length, char_size;
14808 int share_wstr, share_utf8;
14809 unsigned int kind;
14810 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014811
Benjamin Peterson14339b62009-01-31 16:36:08 +000014812 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014813
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014814 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014815 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014816 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014817 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014818 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014819 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014820 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014821 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014822
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014823 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014824 if (self == NULL) {
14825 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014826 return NULL;
14827 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014828 kind = PyUnicode_KIND(unicode);
14829 length = PyUnicode_GET_LENGTH(unicode);
14830
14831 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014832#ifdef Py_DEBUG
14833 _PyUnicode_HASH(self) = -1;
14834#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014835 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014836#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014837 _PyUnicode_STATE(self).interned = 0;
14838 _PyUnicode_STATE(self).kind = kind;
14839 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014840 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014841 _PyUnicode_STATE(self).ready = 1;
14842 _PyUnicode_WSTR(self) = NULL;
14843 _PyUnicode_UTF8_LENGTH(self) = 0;
14844 _PyUnicode_UTF8(self) = NULL;
14845 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014846 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014847
14848 share_utf8 = 0;
14849 share_wstr = 0;
14850 if (kind == PyUnicode_1BYTE_KIND) {
14851 char_size = 1;
14852 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14853 share_utf8 = 1;
14854 }
14855 else if (kind == PyUnicode_2BYTE_KIND) {
14856 char_size = 2;
14857 if (sizeof(wchar_t) == 2)
14858 share_wstr = 1;
14859 }
14860 else {
14861 assert(kind == PyUnicode_4BYTE_KIND);
14862 char_size = 4;
14863 if (sizeof(wchar_t) == 4)
14864 share_wstr = 1;
14865 }
14866
14867 /* Ensure we won't overflow the length. */
14868 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14869 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014870 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014871 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014872 data = PyObject_MALLOC((length + 1) * char_size);
14873 if (data == NULL) {
14874 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014875 goto onError;
14876 }
14877
Victor Stinnerc3c74152011-10-02 20:39:55 +020014878 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014879 if (share_utf8) {
14880 _PyUnicode_UTF8_LENGTH(self) = length;
14881 _PyUnicode_UTF8(self) = data;
14882 }
14883 if (share_wstr) {
14884 _PyUnicode_WSTR_LENGTH(self) = length;
14885 _PyUnicode_WSTR(self) = (wchar_t *)data;
14886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014887
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014888 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014889 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014890 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014891#ifdef Py_DEBUG
14892 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14893#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014894 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014895 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014896
14897onError:
14898 Py_DECREF(unicode);
14899 Py_DECREF(self);
14900 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014901}
14902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014903PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014904"str(object='') -> str\n\
14905str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014906\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014907Create a new string object from the given object. If encoding or\n\
14908errors is specified, then the object must expose a data buffer\n\
14909that will be decoded using the given encoding and error handler.\n\
14910Otherwise, returns the result of object.__str__() (if defined)\n\
14911or repr(object).\n\
14912encoding defaults to sys.getdefaultencoding().\n\
14913errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014914
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014915static PyObject *unicode_iter(PyObject *seq);
14916
Guido van Rossumd57fd912000-03-10 22:53:23 +000014917PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014918 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014919 "str", /* tp_name */
14920 sizeof(PyUnicodeObject), /* tp_size */
14921 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014922 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014923 (destructor)unicode_dealloc, /* tp_dealloc */
14924 0, /* tp_print */
14925 0, /* tp_getattr */
14926 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014927 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014928 unicode_repr, /* tp_repr */
14929 &unicode_as_number, /* tp_as_number */
14930 &unicode_as_sequence, /* tp_as_sequence */
14931 &unicode_as_mapping, /* tp_as_mapping */
14932 (hashfunc) unicode_hash, /* tp_hash*/
14933 0, /* tp_call*/
14934 (reprfunc) unicode_str, /* tp_str */
14935 PyObject_GenericGetAttr, /* tp_getattro */
14936 0, /* tp_setattro */
14937 0, /* tp_as_buffer */
14938 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014939 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014940 unicode_doc, /* tp_doc */
14941 0, /* tp_traverse */
14942 0, /* tp_clear */
14943 PyUnicode_RichCompare, /* tp_richcompare */
14944 0, /* tp_weaklistoffset */
14945 unicode_iter, /* tp_iter */
14946 0, /* tp_iternext */
14947 unicode_methods, /* tp_methods */
14948 0, /* tp_members */
14949 0, /* tp_getset */
14950 &PyBaseObject_Type, /* tp_base */
14951 0, /* tp_dict */
14952 0, /* tp_descr_get */
14953 0, /* tp_descr_set */
14954 0, /* tp_dictoffset */
14955 0, /* tp_init */
14956 0, /* tp_alloc */
14957 unicode_new, /* tp_new */
14958 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014959};
14960
14961/* Initialize the Unicode implementation */
14962
Victor Stinner3a50e702011-10-18 21:21:00 +020014963int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014964{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014965 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014966 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014967 0x000A, /* LINE FEED */
14968 0x000D, /* CARRIAGE RETURN */
14969 0x001C, /* FILE SEPARATOR */
14970 0x001D, /* GROUP SEPARATOR */
14971 0x001E, /* RECORD SEPARATOR */
14972 0x0085, /* NEXT LINE */
14973 0x2028, /* LINE SEPARATOR */
14974 0x2029, /* PARAGRAPH SEPARATOR */
14975 };
14976
Fred Drakee4315f52000-05-09 19:53:39 +000014977 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014978 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014979 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014980 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014981 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014982
Guido van Rossumcacfc072002-05-24 19:01:59 +000014983 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014984 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014985
14986 /* initialize the linebreak bloom filter */
14987 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014988 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014989 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014990
Christian Heimes26532f72013-07-20 14:57:16 +020014991 if (PyType_Ready(&EncodingMapType) < 0)
14992 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014993
Benjamin Petersonc4311282012-10-30 23:21:10 -040014994 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14995 Py_FatalError("Can't initialize field name iterator type");
14996
14997 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14998 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014999
Victor Stinner3a50e702011-10-18 21:21:00 +020015000#ifdef HAVE_MBCS
15001 winver.dwOSVersionInfoSize = sizeof(winver);
15002 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
15003 PyErr_SetFromWindowsErr(0);
15004 return -1;
15005 }
15006#endif
15007 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015008}
15009
15010/* Finalize the Unicode implementation */
15011
Christian Heimesa156e092008-02-16 07:38:31 +000015012int
15013PyUnicode_ClearFreeList(void)
15014{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015015 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015016}
15017
Guido van Rossumd57fd912000-03-10 22:53:23 +000015018void
Thomas Wouters78890102000-07-22 19:25:51 +000015019_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015020{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015021 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015022
Serhiy Storchaka05997252013-01-26 12:14:02 +020015023 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015024
Serhiy Storchaka05997252013-01-26 12:14:02 +020015025 for (i = 0; i < 256; i++)
15026 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015027 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015028 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015029}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015030
Walter Dörwald16807132007-05-25 13:52:07 +000015031void
15032PyUnicode_InternInPlace(PyObject **p)
15033{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015034 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015035 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015036#ifdef Py_DEBUG
15037 assert(s != NULL);
15038 assert(_PyUnicode_CHECK(s));
15039#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015040 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015041 return;
15042#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015043 /* If it's a subclass, we don't really know what putting
15044 it in the interned dict might do. */
15045 if (!PyUnicode_CheckExact(s))
15046 return;
15047 if (PyUnicode_CHECK_INTERNED(s))
15048 return;
15049 if (interned == NULL) {
15050 interned = PyDict_New();
15051 if (interned == NULL) {
15052 PyErr_Clear(); /* Don't leave an exception */
15053 return;
15054 }
15055 }
15056 /* It might be that the GetItem call fails even
15057 though the key is present in the dictionary,
15058 namely when this happens during a stack overflow. */
15059 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015060 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015061 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015062
Victor Stinnerf0335102013-04-14 19:13:03 +020015063 if (t) {
15064 Py_INCREF(t);
15065 Py_DECREF(*p);
15066 *p = t;
15067 return;
15068 }
Walter Dörwald16807132007-05-25 13:52:07 +000015069
Benjamin Peterson14339b62009-01-31 16:36:08 +000015070 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015071 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015072 PyErr_Clear();
15073 PyThreadState_GET()->recursion_critical = 0;
15074 return;
15075 }
15076 PyThreadState_GET()->recursion_critical = 0;
15077 /* The two references in interned are not counted by refcnt.
15078 The deallocator will take care of this */
15079 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015080 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015081}
15082
15083void
15084PyUnicode_InternImmortal(PyObject **p)
15085{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 PyUnicode_InternInPlace(p);
15087 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015088 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015089 Py_INCREF(*p);
15090 }
Walter Dörwald16807132007-05-25 13:52:07 +000015091}
15092
15093PyObject *
15094PyUnicode_InternFromString(const char *cp)
15095{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015096 PyObject *s = PyUnicode_FromString(cp);
15097 if (s == NULL)
15098 return NULL;
15099 PyUnicode_InternInPlace(&s);
15100 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015101}
15102
Alexander Belopolsky40018472011-02-26 01:02:56 +000015103void
15104_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015105{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015106 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015107 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015108 Py_ssize_t i, n;
15109 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015110
Benjamin Peterson14339b62009-01-31 16:36:08 +000015111 if (interned == NULL || !PyDict_Check(interned))
15112 return;
15113 keys = PyDict_Keys(interned);
15114 if (keys == NULL || !PyList_Check(keys)) {
15115 PyErr_Clear();
15116 return;
15117 }
Walter Dörwald16807132007-05-25 13:52:07 +000015118
Benjamin Peterson14339b62009-01-31 16:36:08 +000015119 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15120 detector, interned unicode strings are not forcibly deallocated;
15121 rather, we give them their stolen references back, and then clear
15122 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015123
Benjamin Peterson14339b62009-01-31 16:36:08 +000015124 n = PyList_GET_SIZE(keys);
15125 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015126 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015127 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015128 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015129 if (PyUnicode_READY(s) == -1) {
15130 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015131 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015132 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015133 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015134 case SSTATE_NOT_INTERNED:
15135 /* XXX Shouldn't happen */
15136 break;
15137 case SSTATE_INTERNED_IMMORTAL:
15138 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015139 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015140 break;
15141 case SSTATE_INTERNED_MORTAL:
15142 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015143 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015144 break;
15145 default:
15146 Py_FatalError("Inconsistent interned string state.");
15147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015148 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015149 }
15150 fprintf(stderr, "total size of all interned strings: "
15151 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15152 "mortal/immortal\n", mortal_size, immortal_size);
15153 Py_DECREF(keys);
15154 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015155 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015156}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015157
15158
15159/********************* Unicode Iterator **************************/
15160
15161typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015162 PyObject_HEAD
15163 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015164 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165} unicodeiterobject;
15166
15167static void
15168unicodeiter_dealloc(unicodeiterobject *it)
15169{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 _PyObject_GC_UNTRACK(it);
15171 Py_XDECREF(it->it_seq);
15172 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015173}
15174
15175static int
15176unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 Py_VISIT(it->it_seq);
15179 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015180}
15181
15182static PyObject *
15183unicodeiter_next(unicodeiterobject *it)
15184{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015185 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015186
Benjamin Peterson14339b62009-01-31 16:36:08 +000015187 assert(it != NULL);
15188 seq = it->it_seq;
15189 if (seq == NULL)
15190 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015191 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015193 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15194 int kind = PyUnicode_KIND(seq);
15195 void *data = PyUnicode_DATA(seq);
15196 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15197 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015198 if (item != NULL)
15199 ++it->it_index;
15200 return item;
15201 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015202
Benjamin Peterson14339b62009-01-31 16:36:08 +000015203 Py_DECREF(seq);
15204 it->it_seq = NULL;
15205 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015206}
15207
15208static PyObject *
15209unicodeiter_len(unicodeiterobject *it)
15210{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015211 Py_ssize_t len = 0;
15212 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015213 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015215}
15216
15217PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15218
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015219static PyObject *
15220unicodeiter_reduce(unicodeiterobject *it)
15221{
15222 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015223 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015224 it->it_seq, it->it_index);
15225 } else {
15226 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15227 if (u == NULL)
15228 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015229 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015230 }
15231}
15232
15233PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15234
15235static PyObject *
15236unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15237{
15238 Py_ssize_t index = PyLong_AsSsize_t(state);
15239 if (index == -1 && PyErr_Occurred())
15240 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015241 if (it->it_seq != NULL) {
15242 if (index < 0)
15243 index = 0;
15244 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15245 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15246 it->it_index = index;
15247 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015248 Py_RETURN_NONE;
15249}
15250
15251PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15252
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015253static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015255 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015256 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15257 reduce_doc},
15258 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15259 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015260 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015261};
15262
15263PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015264 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15265 "str_iterator", /* tp_name */
15266 sizeof(unicodeiterobject), /* tp_basicsize */
15267 0, /* tp_itemsize */
15268 /* methods */
15269 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15270 0, /* tp_print */
15271 0, /* tp_getattr */
15272 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015273 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015274 0, /* tp_repr */
15275 0, /* tp_as_number */
15276 0, /* tp_as_sequence */
15277 0, /* tp_as_mapping */
15278 0, /* tp_hash */
15279 0, /* tp_call */
15280 0, /* tp_str */
15281 PyObject_GenericGetAttr, /* tp_getattro */
15282 0, /* tp_setattro */
15283 0, /* tp_as_buffer */
15284 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15285 0, /* tp_doc */
15286 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15287 0, /* tp_clear */
15288 0, /* tp_richcompare */
15289 0, /* tp_weaklistoffset */
15290 PyObject_SelfIter, /* tp_iter */
15291 (iternextfunc)unicodeiter_next, /* tp_iternext */
15292 unicodeiter_methods, /* tp_methods */
15293 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015294};
15295
15296static PyObject *
15297unicode_iter(PyObject *seq)
15298{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015299 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015300
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 if (!PyUnicode_Check(seq)) {
15302 PyErr_BadInternalCall();
15303 return NULL;
15304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015305 if (PyUnicode_READY(seq) == -1)
15306 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015307 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15308 if (it == NULL)
15309 return NULL;
15310 it->it_index = 0;
15311 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015312 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015313 _PyObject_GC_TRACK(it);
15314 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015315}
15316
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015317
15318size_t
15319Py_UNICODE_strlen(const Py_UNICODE *u)
15320{
15321 int res = 0;
15322 while(*u++)
15323 res++;
15324 return res;
15325}
15326
15327Py_UNICODE*
15328Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15329{
15330 Py_UNICODE *u = s1;
15331 while ((*u++ = *s2++));
15332 return s1;
15333}
15334
15335Py_UNICODE*
15336Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15337{
15338 Py_UNICODE *u = s1;
15339 while ((*u++ = *s2++))
15340 if (n-- == 0)
15341 break;
15342 return s1;
15343}
15344
15345Py_UNICODE*
15346Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15347{
15348 Py_UNICODE *u1 = s1;
15349 u1 += Py_UNICODE_strlen(u1);
15350 Py_UNICODE_strcpy(u1, s2);
15351 return s1;
15352}
15353
15354int
15355Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15356{
15357 while (*s1 && *s2 && *s1 == *s2)
15358 s1++, s2++;
15359 if (*s1 && *s2)
15360 return (*s1 < *s2) ? -1 : +1;
15361 if (*s1)
15362 return 1;
15363 if (*s2)
15364 return -1;
15365 return 0;
15366}
15367
15368int
15369Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15370{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015371 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015372 for (; n != 0; n--) {
15373 u1 = *s1;
15374 u2 = *s2;
15375 if (u1 != u2)
15376 return (u1 < u2) ? -1 : +1;
15377 if (u1 == '\0')
15378 return 0;
15379 s1++;
15380 s2++;
15381 }
15382 return 0;
15383}
15384
15385Py_UNICODE*
15386Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15387{
15388 const Py_UNICODE *p;
15389 for (p = s; *p; p++)
15390 if (*p == c)
15391 return (Py_UNICODE*)p;
15392 return NULL;
15393}
15394
15395Py_UNICODE*
15396Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15397{
15398 const Py_UNICODE *p;
15399 p = s + Py_UNICODE_strlen(s);
15400 while (p != s) {
15401 p--;
15402 if (*p == c)
15403 return (Py_UNICODE*)p;
15404 }
15405 return NULL;
15406}
Victor Stinner331ea922010-08-10 16:37:20 +000015407
Victor Stinner71133ff2010-09-01 23:43:53 +000015408Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015409PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015410{
Victor Stinner577db2c2011-10-11 22:12:48 +020015411 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015412 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015414 if (!PyUnicode_Check(unicode)) {
15415 PyErr_BadArgument();
15416 return NULL;
15417 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015418 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015419 if (u == NULL)
15420 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015421 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015422 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015423 PyErr_NoMemory();
15424 return NULL;
15425 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015426 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015427 size *= sizeof(Py_UNICODE);
15428 copy = PyMem_Malloc(size);
15429 if (copy == NULL) {
15430 PyErr_NoMemory();
15431 return NULL;
15432 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015433 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015434 return copy;
15435}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015436
Georg Brandl66c221e2010-10-14 07:04:07 +000015437/* A _string module, to export formatter_parser and formatter_field_name_split
15438 to the string.Formatter class implemented in Python. */
15439
15440static PyMethodDef _string_methods[] = {
15441 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15442 METH_O, PyDoc_STR("split the argument as a field name")},
15443 {"formatter_parser", (PyCFunction) formatter_parser,
15444 METH_O, PyDoc_STR("parse the argument as a format string")},
15445 {NULL, NULL}
15446};
15447
15448static struct PyModuleDef _string_module = {
15449 PyModuleDef_HEAD_INIT,
15450 "_string",
15451 PyDoc_STR("string helper module"),
15452 0,
15453 _string_methods,
15454 NULL,
15455 NULL,
15456 NULL,
15457 NULL
15458};
15459
15460PyMODINIT_FUNC
15461PyInit__string(void)
15462{
15463 return PyModule_Create(&_string_module);
15464}
15465
15466
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015467#ifdef __cplusplus
15468}
15469#endif