blob: 8a13f2cdd74223f06fa439701d4c62369c10e116 [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,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002943 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 Py_TYPE(obj)->tp_name);
2945 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002946 }
Tim Petersced69f82003-09-16 20:30:58 +00002947
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002949 PyBuffer_Release(&buffer);
2950 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002952
Serhiy Storchaka05997252013-01-26 12:14:02 +02002953 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002954 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002955 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002956}
2957
Victor Stinner600d3be2010-06-10 12:00:55 +00002958/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002959 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2960 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002961int
2962_Py_normalize_encoding(const char *encoding,
2963 char *lower,
2964 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002965{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002966 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002967 char *l;
2968 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002969
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002970 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002971 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002972 if (lower_len < 6)
2973 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002974 strcpy(lower, "utf-8");
2975 return 1;
2976 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002977 e = encoding;
2978 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002979 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002980 while (*e) {
2981 if (l == l_end)
2982 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002983 if (Py_ISUPPER(*e)) {
2984 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002985 }
2986 else if (*e == '_') {
2987 *l++ = '-';
2988 e++;
2989 }
2990 else {
2991 *l++ = *e++;
2992 }
2993 }
2994 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002995 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002996}
2997
Alexander Belopolsky40018472011-02-26 01:02:56 +00002998PyObject *
2999PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003000 Py_ssize_t size,
3001 const char *encoding,
3002 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003003{
3004 PyObject *buffer = NULL, *unicode;
3005 Py_buffer info;
3006 char lower[11]; /* Enough for any encoding shortcut */
3007
Fred Drakee4315f52000-05-09 19:53:39 +00003008 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003009 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003010 if ((strcmp(lower, "utf-8") == 0) ||
3011 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003012 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003013 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003014 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003015 (strcmp(lower, "iso-8859-1") == 0) ||
3016 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003017 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003018#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003019 else if (strcmp(lower, "mbcs") == 0)
3020 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003021#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003022 else if (strcmp(lower, "ascii") == 0)
3023 return PyUnicode_DecodeASCII(s, size, errors);
3024 else if (strcmp(lower, "utf-16") == 0)
3025 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3026 else if (strcmp(lower, "utf-32") == 0)
3027 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003029
3030 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003031 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003032 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003033 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003034 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003035 if (buffer == NULL)
3036 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003037 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003038 if (unicode == NULL)
3039 goto onError;
3040 if (!PyUnicode_Check(unicode)) {
3041 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003042 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3043 "use codecs.decode() to decode to arbitrary types",
3044 encoding,
3045 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003046 Py_DECREF(unicode);
3047 goto onError;
3048 }
3049 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003050 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003051
Benjamin Peterson29060642009-01-31 22:14:21 +00003052 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003053 Py_XDECREF(buffer);
3054 return NULL;
3055}
3056
Alexander Belopolsky40018472011-02-26 01:02:56 +00003057PyObject *
3058PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003059 const char *encoding,
3060 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061{
3062 PyObject *v;
3063
3064 if (!PyUnicode_Check(unicode)) {
3065 PyErr_BadArgument();
3066 goto onError;
3067 }
3068
3069 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003070 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003071
3072 /* Decode via the codec registry */
3073 v = PyCodec_Decode(unicode, encoding, errors);
3074 if (v == NULL)
3075 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003076 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003077
Benjamin Peterson29060642009-01-31 22:14:21 +00003078 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003079 return NULL;
3080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 const char *encoding,
3085 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003086{
3087 PyObject *v;
3088
3089 if (!PyUnicode_Check(unicode)) {
3090 PyErr_BadArgument();
3091 goto onError;
3092 }
3093
3094 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003095 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003096
3097 /* Decode via the codec registry */
3098 v = PyCodec_Decode(unicode, encoding, errors);
3099 if (v == NULL)
3100 goto onError;
3101 if (!PyUnicode_Check(v)) {
3102 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003103 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3104 "use codecs.decode() to decode to arbitrary types",
3105 encoding,
3106 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003107 Py_DECREF(v);
3108 goto onError;
3109 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003110 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003111
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003113 return NULL;
3114}
3115
Alexander Belopolsky40018472011-02-26 01:02:56 +00003116PyObject *
3117PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003118 Py_ssize_t size,
3119 const char *encoding,
3120 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121{
3122 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003123
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124 unicode = PyUnicode_FromUnicode(s, size);
3125 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003127 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3128 Py_DECREF(unicode);
3129 return v;
3130}
3131
Alexander Belopolsky40018472011-02-26 01:02:56 +00003132PyObject *
3133PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003134 const char *encoding,
3135 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136{
3137 PyObject *v;
3138
3139 if (!PyUnicode_Check(unicode)) {
3140 PyErr_BadArgument();
3141 goto onError;
3142 }
3143
3144 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003145 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003146
3147 /* Encode via the codec registry */
3148 v = PyCodec_Encode(unicode, encoding, errors);
3149 if (v == NULL)
3150 goto onError;
3151 return v;
3152
Benjamin Peterson29060642009-01-31 22:14:21 +00003153 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003154 return NULL;
3155}
3156
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157static size_t
3158wcstombs_errorpos(const wchar_t *wstr)
3159{
3160 size_t len;
3161#if SIZEOF_WCHAR_T == 2
3162 wchar_t buf[3];
3163#else
3164 wchar_t buf[2];
3165#endif
3166 char outbuf[MB_LEN_MAX];
3167 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003168
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003169#if SIZEOF_WCHAR_T == 2
3170 buf[2] = 0;
3171#else
3172 buf[1] = 0;
3173#endif
3174 start = wstr;
3175 while (*wstr != L'\0')
3176 {
3177 previous = wstr;
3178#if SIZEOF_WCHAR_T == 2
3179 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3180 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3181 {
3182 buf[0] = wstr[0];
3183 buf[1] = wstr[1];
3184 wstr += 2;
3185 }
3186 else {
3187 buf[0] = *wstr;
3188 buf[1] = 0;
3189 wstr++;
3190 }
3191#else
3192 buf[0] = *wstr;
3193 wstr++;
3194#endif
3195 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003196 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003198 }
3199
3200 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003201 return 0;
3202}
3203
Victor Stinner1b579672011-12-17 05:47:23 +01003204static int
3205locale_error_handler(const char *errors, int *surrogateescape)
3206{
3207 if (errors == NULL) {
3208 *surrogateescape = 0;
3209 return 0;
3210 }
3211
3212 if (strcmp(errors, "strict") == 0) {
3213 *surrogateescape = 0;
3214 return 0;
3215 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003216 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003217 *surrogateescape = 1;
3218 return 0;
3219 }
3220 PyErr_Format(PyExc_ValueError,
3221 "only 'strict' and 'surrogateescape' error handlers "
3222 "are supported, not '%s'",
3223 errors);
3224 return -1;
3225}
3226
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003227PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003228PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003229{
3230 Py_ssize_t wlen, wlen2;
3231 wchar_t *wstr;
3232 PyObject *bytes = NULL;
3233 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003234 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003235 PyObject *exc;
3236 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003237 int surrogateescape;
3238
3239 if (locale_error_handler(errors, &surrogateescape) < 0)
3240 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003241
3242 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3243 if (wstr == NULL)
3244 return NULL;
3245
3246 wlen2 = wcslen(wstr);
3247 if (wlen2 != wlen) {
3248 PyMem_Free(wstr);
3249 PyErr_SetString(PyExc_TypeError, "embedded null character");
3250 return NULL;
3251 }
3252
3253 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003254 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003255 char *str;
3256
3257 str = _Py_wchar2char(wstr, &error_pos);
3258 if (str == NULL) {
3259 if (error_pos == (size_t)-1) {
3260 PyErr_NoMemory();
3261 PyMem_Free(wstr);
3262 return NULL;
3263 }
3264 else {
3265 goto encode_error;
3266 }
3267 }
3268 PyMem_Free(wstr);
3269
3270 bytes = PyBytes_FromString(str);
3271 PyMem_Free(str);
3272 }
3273 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003274 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003275 size_t len, len2;
3276
3277 len = wcstombs(NULL, wstr, 0);
3278 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003279 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 goto encode_error;
3281 }
3282
3283 bytes = PyBytes_FromStringAndSize(NULL, len);
3284 if (bytes == NULL) {
3285 PyMem_Free(wstr);
3286 return NULL;
3287 }
3288
3289 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3290 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003291 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003292 goto encode_error;
3293 }
3294 PyMem_Free(wstr);
3295 }
3296 return bytes;
3297
3298encode_error:
3299 errmsg = strerror(errno);
3300 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003301
3302 if (error_pos == (size_t)-1)
3303 error_pos = wcstombs_errorpos(wstr);
3304
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003305 PyMem_Free(wstr);
3306 Py_XDECREF(bytes);
3307
Victor Stinner2f197072011-12-17 07:08:30 +01003308 if (errmsg != NULL) {
3309 size_t errlen;
3310 wstr = _Py_char2wchar(errmsg, &errlen);
3311 if (wstr != NULL) {
3312 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003313 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003314 } else
3315 errmsg = NULL;
3316 }
3317 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003318 reason = PyUnicode_FromString(
3319 "wcstombs() encountered an unencodable "
3320 "wide character");
3321 if (reason == NULL)
3322 return NULL;
3323
3324 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3325 "locale", unicode,
3326 (Py_ssize_t)error_pos,
3327 (Py_ssize_t)(error_pos+1),
3328 reason);
3329 Py_DECREF(reason);
3330 if (exc != NULL) {
3331 PyCodec_StrictErrors(exc);
3332 Py_XDECREF(exc);
3333 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003334 return NULL;
3335}
3336
Victor Stinnerad158722010-10-27 00:25:46 +00003337PyObject *
3338PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003339{
Victor Stinner99b95382011-07-04 14:23:54 +02003340#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003341 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003342#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003343 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003344#else
Victor Stinner793b5312011-04-27 00:24:21 +02003345 PyInterpreterState *interp = PyThreadState_GET()->interp;
3346 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3347 cannot use it to encode and decode filenames before it is loaded. Load
3348 the Python codec requires to encode at least its own filename. Use the C
3349 version of the locale codec until the codec registry is initialized and
3350 the Python codec is loaded.
3351
3352 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3353 cannot only rely on it: check also interp->fscodec_initialized for
3354 subinterpreters. */
3355 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003356 return PyUnicode_AsEncodedString(unicode,
3357 Py_FileSystemDefaultEncoding,
3358 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003359 }
3360 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003361 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003362 }
Victor Stinnerad158722010-10-27 00:25:46 +00003363#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003364}
3365
Alexander Belopolsky40018472011-02-26 01:02:56 +00003366PyObject *
3367PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003368 const char *encoding,
3369 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003370{
3371 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003372 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003373
Guido van Rossumd57fd912000-03-10 22:53:23 +00003374 if (!PyUnicode_Check(unicode)) {
3375 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003377 }
Fred Drakee4315f52000-05-09 19:53:39 +00003378
Fred Drakee4315f52000-05-09 19:53:39 +00003379 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003380 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003381 if ((strcmp(lower, "utf-8") == 0) ||
3382 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003383 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003384 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003385 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003386 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003388 }
Victor Stinner37296e82010-06-10 13:36:23 +00003389 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003390 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003391 (strcmp(lower, "iso-8859-1") == 0) ||
3392 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003394#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003395 else if (strcmp(lower, "mbcs") == 0)
3396 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003397#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003398 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003400 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003401
3402 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003403 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003404 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003405 return NULL;
3406
3407 /* The normal path */
3408 if (PyBytes_Check(v))
3409 return v;
3410
3411 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003412 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003413 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003414 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003415
3416 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003417 "encoder %s returned bytearray instead of bytes; "
3418 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003419 encoding);
3420 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003421 Py_DECREF(v);
3422 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003423 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003425 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3426 Py_DECREF(v);
3427 return b;
3428 }
3429
3430 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003431 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3432 "use codecs.encode() to encode to arbitrary types",
3433 encoding,
3434 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003435 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003436 return NULL;
3437}
3438
Alexander Belopolsky40018472011-02-26 01:02:56 +00003439PyObject *
3440PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003441 const char *encoding,
3442 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003443{
3444 PyObject *v;
3445
3446 if (!PyUnicode_Check(unicode)) {
3447 PyErr_BadArgument();
3448 goto onError;
3449 }
3450
3451 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003452 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003453
3454 /* Encode via the codec registry */
3455 v = PyCodec_Encode(unicode, encoding, errors);
3456 if (v == NULL)
3457 goto onError;
3458 if (!PyUnicode_Check(v)) {
3459 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003460 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3461 "use codecs.encode() to encode to arbitrary types",
3462 encoding,
3463 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003464 Py_DECREF(v);
3465 goto onError;
3466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003467 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003468
Benjamin Peterson29060642009-01-31 22:14:21 +00003469 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003470 return NULL;
3471}
3472
Victor Stinner2f197072011-12-17 07:08:30 +01003473static size_t
3474mbstowcs_errorpos(const char *str, size_t len)
3475{
3476#ifdef HAVE_MBRTOWC
3477 const char *start = str;
3478 mbstate_t mbs;
3479 size_t converted;
3480 wchar_t ch;
3481
3482 memset(&mbs, 0, sizeof mbs);
3483 while (len)
3484 {
3485 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3486 if (converted == 0)
3487 /* Reached end of string */
3488 break;
3489 if (converted == (size_t)-1 || converted == (size_t)-2) {
3490 /* Conversion error or incomplete character */
3491 return str - start;
3492 }
3493 else {
3494 str += converted;
3495 len -= converted;
3496 }
3497 }
3498 /* failed to find the undecodable byte sequence */
3499 return 0;
3500#endif
3501 return 0;
3502}
3503
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003504PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003505PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003506 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003507{
3508 wchar_t smallbuf[256];
3509 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3510 wchar_t *wstr;
3511 size_t wlen, wlen2;
3512 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003513 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003514 size_t error_pos;
3515 char *errmsg;
3516 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003517
3518 if (locale_error_handler(errors, &surrogateescape) < 0)
3519 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520
3521 if (str[len] != '\0' || len != strlen(str)) {
3522 PyErr_SetString(PyExc_TypeError, "embedded null character");
3523 return NULL;
3524 }
3525
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003526 if (surrogateescape) {
3527 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003528 wstr = _Py_char2wchar(str, &wlen);
3529 if (wstr == NULL) {
3530 if (wlen == (size_t)-1)
3531 PyErr_NoMemory();
3532 else
3533 PyErr_SetFromErrno(PyExc_OSError);
3534 return NULL;
3535 }
3536
3537 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003538 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003539 }
3540 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003541 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003542#ifndef HAVE_BROKEN_MBSTOWCS
3543 wlen = mbstowcs(NULL, str, 0);
3544#else
3545 wlen = len;
3546#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003547 if (wlen == (size_t)-1)
3548 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 if (wlen+1 <= smallbuf_len) {
3550 wstr = smallbuf;
3551 }
3552 else {
3553 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3554 return PyErr_NoMemory();
3555
3556 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3557 if (!wstr)
3558 return PyErr_NoMemory();
3559 }
3560
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003561 wlen2 = mbstowcs(wstr, str, wlen+1);
3562 if (wlen2 == (size_t)-1) {
3563 if (wstr != smallbuf)
3564 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003565 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003566 }
3567#ifdef HAVE_BROKEN_MBSTOWCS
3568 assert(wlen2 == wlen);
3569#endif
3570 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3571 if (wstr != smallbuf)
3572 PyMem_Free(wstr);
3573 }
3574 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003575
3576decode_error:
3577 errmsg = strerror(errno);
3578 assert(errmsg != NULL);
3579
3580 error_pos = mbstowcs_errorpos(str, len);
3581 if (errmsg != NULL) {
3582 size_t errlen;
3583 wstr = _Py_char2wchar(errmsg, &errlen);
3584 if (wstr != NULL) {
3585 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003586 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003587 } else
3588 errmsg = NULL;
3589 }
3590 if (errmsg == NULL)
3591 reason = PyUnicode_FromString(
3592 "mbstowcs() encountered an invalid multibyte sequence");
3593 if (reason == NULL)
3594 return NULL;
3595
3596 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3597 "locale", str, len,
3598 (Py_ssize_t)error_pos,
3599 (Py_ssize_t)(error_pos+1),
3600 reason);
3601 Py_DECREF(reason);
3602 if (exc != NULL) {
3603 PyCodec_StrictErrors(exc);
3604 Py_XDECREF(exc);
3605 }
3606 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003607}
3608
3609PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003610PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003611{
3612 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003613 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003614}
3615
3616
3617PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003618PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003619 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003620 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3621}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003622
Christian Heimes5894ba72007-11-04 11:43:14 +00003623PyObject*
3624PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3625{
Victor Stinner99b95382011-07-04 14:23:54 +02003626#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003627 return PyUnicode_DecodeMBCS(s, size, NULL);
3628#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003629 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003630#else
Victor Stinner793b5312011-04-27 00:24:21 +02003631 PyInterpreterState *interp = PyThreadState_GET()->interp;
3632 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3633 cannot use it to encode and decode filenames before it is loaded. Load
3634 the Python codec requires to encode at least its own filename. Use the C
3635 version of the locale codec until the codec registry is initialized and
3636 the Python codec is loaded.
3637
3638 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3639 cannot only rely on it: check also interp->fscodec_initialized for
3640 subinterpreters. */
3641 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003642 return PyUnicode_Decode(s, size,
3643 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003644 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003645 }
3646 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003647 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003648 }
Victor Stinnerad158722010-10-27 00:25:46 +00003649#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003650}
3651
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652
3653int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003654_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003655{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003656 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003657
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003658 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003659 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003660 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3661 PyUnicode_GET_LENGTH(str), '\0', 1);
3662 if (pos == -1)
3663 return 0;
3664 else
3665 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003666}
3667
Antoine Pitrou13348842012-01-29 18:36:34 +01003668int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003669PyUnicode_FSConverter(PyObject* arg, void* addr)
3670{
3671 PyObject *output = NULL;
3672 Py_ssize_t size;
3673 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003674 if (arg == NULL) {
3675 Py_DECREF(*(PyObject**)addr);
3676 return 1;
3677 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003678 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003679 output = arg;
3680 Py_INCREF(output);
3681 }
3682 else {
3683 arg = PyUnicode_FromObject(arg);
3684 if (!arg)
3685 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003686 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003687 Py_DECREF(arg);
3688 if (!output)
3689 return 0;
3690 if (!PyBytes_Check(output)) {
3691 Py_DECREF(output);
3692 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3693 return 0;
3694 }
3695 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003696 size = PyBytes_GET_SIZE(output);
3697 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003698 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003699 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003700 Py_DECREF(output);
3701 return 0;
3702 }
3703 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003704 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003705}
3706
3707
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003708int
3709PyUnicode_FSDecoder(PyObject* arg, void* addr)
3710{
3711 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003712 if (arg == NULL) {
3713 Py_DECREF(*(PyObject**)addr);
3714 return 1;
3715 }
3716 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003717 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003719 output = arg;
3720 Py_INCREF(output);
3721 }
3722 else {
3723 arg = PyBytes_FromObject(arg);
3724 if (!arg)
3725 return 0;
3726 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3727 PyBytes_GET_SIZE(arg));
3728 Py_DECREF(arg);
3729 if (!output)
3730 return 0;
3731 if (!PyUnicode_Check(output)) {
3732 Py_DECREF(output);
3733 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3734 return 0;
3735 }
3736 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003737 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003738 Py_DECREF(output);
3739 return 0;
3740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003741 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003742 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003743 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3744 Py_DECREF(output);
3745 return 0;
3746 }
3747 *(PyObject**)addr = output;
3748 return Py_CLEANUP_SUPPORTED;
3749}
3750
3751
Martin v. Löwis5b222132007-06-10 09:51:05 +00003752char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003753PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003754{
Christian Heimesf3863112007-11-22 07:46:41 +00003755 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003756
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003757 if (!PyUnicode_Check(unicode)) {
3758 PyErr_BadArgument();
3759 return NULL;
3760 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003761 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003762 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003763
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003764 if (PyUnicode_UTF8(unicode) == NULL) {
3765 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3767 if (bytes == NULL)
3768 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3770 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003771 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003772 Py_DECREF(bytes);
3773 return NULL;
3774 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003775 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3776 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3777 PyBytes_AS_STRING(bytes),
3778 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003779 Py_DECREF(bytes);
3780 }
3781
3782 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003783 *psize = PyUnicode_UTF8_LENGTH(unicode);
3784 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003785}
3786
3787char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003789{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003790 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3791}
3792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793Py_UNICODE *
3794PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3795{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796 const unsigned char *one_byte;
3797#if SIZEOF_WCHAR_T == 4
3798 const Py_UCS2 *two_bytes;
3799#else
3800 const Py_UCS4 *four_bytes;
3801 const Py_UCS4 *ucs4_end;
3802 Py_ssize_t num_surrogates;
3803#endif
3804 wchar_t *w;
3805 wchar_t *wchar_end;
3806
3807 if (!PyUnicode_Check(unicode)) {
3808 PyErr_BadArgument();
3809 return NULL;
3810 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003811 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003813 assert(_PyUnicode_KIND(unicode) != 0);
3814 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003817#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3819 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003820 num_surrogates = 0;
3821
3822 for (; four_bytes < ucs4_end; ++four_bytes) {
3823 if (*four_bytes > 0xFFFF)
3824 ++num_surrogates;
3825 }
3826
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3828 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3829 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 PyErr_NoMemory();
3831 return NULL;
3832 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003833 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003834
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 w = _PyUnicode_WSTR(unicode);
3836 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3837 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003838 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3839 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003840 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003842 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3843 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003844 }
3845 else
3846 *w = *four_bytes;
3847
3848 if (w > wchar_end) {
3849 assert(0 && "Miscalculated string end");
3850 }
3851 }
3852 *w = 0;
3853#else
3854 /* sizeof(wchar_t) == 4 */
3855 Py_FatalError("Impossible unicode object state, wstr and str "
3856 "should share memory already.");
3857 return NULL;
3858#endif
3859 }
3860 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003861 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3862 (_PyUnicode_LENGTH(unicode) + 1));
3863 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003864 PyErr_NoMemory();
3865 return NULL;
3866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3868 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3869 w = _PyUnicode_WSTR(unicode);
3870 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003872 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3873 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 for (; w < wchar_end; ++one_byte, ++w)
3875 *w = *one_byte;
3876 /* null-terminate the wstr */
3877 *w = 0;
3878 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003880#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003882 for (; w < wchar_end; ++two_bytes, ++w)
3883 *w = *two_bytes;
3884 /* null-terminate the wstr */
3885 *w = 0;
3886#else
3887 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003888 PyObject_FREE(_PyUnicode_WSTR(unicode));
3889 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 Py_FatalError("Impossible unicode object state, wstr "
3891 "and str should share memory already.");
3892 return NULL;
3893#endif
3894 }
3895 else {
3896 assert(0 && "This should never happen.");
3897 }
3898 }
3899 }
3900 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003901 *size = PyUnicode_WSTR_LENGTH(unicode);
3902 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003903}
3904
Alexander Belopolsky40018472011-02-26 01:02:56 +00003905Py_UNICODE *
3906PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003909}
3910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911
Alexander Belopolsky40018472011-02-26 01:02:56 +00003912Py_ssize_t
3913PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003914{
3915 if (!PyUnicode_Check(unicode)) {
3916 PyErr_BadArgument();
3917 goto onError;
3918 }
3919 return PyUnicode_GET_SIZE(unicode);
3920
Benjamin Peterson29060642009-01-31 22:14:21 +00003921 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003922 return -1;
3923}
3924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925Py_ssize_t
3926PyUnicode_GetLength(PyObject *unicode)
3927{
Victor Stinner07621332012-06-16 04:53:46 +02003928 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003929 PyErr_BadArgument();
3930 return -1;
3931 }
Victor Stinner07621332012-06-16 04:53:46 +02003932 if (PyUnicode_READY(unicode) == -1)
3933 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003934 return PyUnicode_GET_LENGTH(unicode);
3935}
3936
3937Py_UCS4
3938PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3939{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003940 void *data;
3941 int kind;
3942
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003943 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3944 PyErr_BadArgument();
3945 return (Py_UCS4)-1;
3946 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003947 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003948 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003949 return (Py_UCS4)-1;
3950 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003951 data = PyUnicode_DATA(unicode);
3952 kind = PyUnicode_KIND(unicode);
3953 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954}
3955
3956int
3957PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3958{
3959 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003960 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003961 return -1;
3962 }
Victor Stinner488fa492011-12-12 00:01:39 +01003963 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003964 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003965 PyErr_SetString(PyExc_IndexError, "string index out of range");
3966 return -1;
3967 }
Victor Stinner488fa492011-12-12 00:01:39 +01003968 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003969 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003970 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3971 PyErr_SetString(PyExc_ValueError, "character out of range");
3972 return -1;
3973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003974 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3975 index, ch);
3976 return 0;
3977}
3978
Alexander Belopolsky40018472011-02-26 01:02:56 +00003979const char *
3980PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003981{
Victor Stinner42cb4622010-09-01 19:39:01 +00003982 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003983}
3984
Victor Stinner554f3f02010-06-16 23:33:54 +00003985/* create or adjust a UnicodeDecodeError */
3986static void
3987make_decode_exception(PyObject **exceptionObject,
3988 const char *encoding,
3989 const char *input, Py_ssize_t length,
3990 Py_ssize_t startpos, Py_ssize_t endpos,
3991 const char *reason)
3992{
3993 if (*exceptionObject == NULL) {
3994 *exceptionObject = PyUnicodeDecodeError_Create(
3995 encoding, input, length, startpos, endpos, reason);
3996 }
3997 else {
3998 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3999 goto onError;
4000 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4001 goto onError;
4002 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4003 goto onError;
4004 }
4005 return;
4006
4007onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004008 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004009}
4010
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004011#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004012/* error handling callback helper:
4013 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004014 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004015 and adjust various state variables.
4016 return 0 on success, -1 on error
4017*/
4018
Alexander Belopolsky40018472011-02-26 01:02:56 +00004019static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004020unicode_decode_call_errorhandler_wchar(
4021 const char *errors, PyObject **errorHandler,
4022 const char *encoding, const char *reason,
4023 const char **input, const char **inend, Py_ssize_t *startinpos,
4024 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4025 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004027 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004028
4029 PyObject *restuple = NULL;
4030 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004031 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004032 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004033 Py_ssize_t requiredsize;
4034 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004035 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004036 wchar_t *repwstr;
4037 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004038
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004039 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4040 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004041
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004042 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 *errorHandler = PyCodec_LookupError(errors);
4044 if (*errorHandler == NULL)
4045 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004046 }
4047
Victor Stinner554f3f02010-06-16 23:33:54 +00004048 make_decode_exception(exceptionObject,
4049 encoding,
4050 *input, *inend - *input,
4051 *startinpos, *endinpos,
4052 reason);
4053 if (*exceptionObject == NULL)
4054 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004055
4056 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4057 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004058 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004059 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004060 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004061 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062 }
4063 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004064 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004065
4066 /* Copy back the bytes variables, which might have been modified by the
4067 callback */
4068 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4069 if (!inputobj)
4070 goto onError;
4071 if (!PyBytes_Check(inputobj)) {
4072 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4073 }
4074 *input = PyBytes_AS_STRING(inputobj);
4075 insize = PyBytes_GET_SIZE(inputobj);
4076 *inend = *input + insize;
4077 /* we can DECREF safely, as the exception has another reference,
4078 so the object won't go away. */
4079 Py_DECREF(inputobj);
4080
4081 if (newpos<0)
4082 newpos = insize+newpos;
4083 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004084 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004085 goto onError;
4086 }
4087
4088 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4089 if (repwstr == NULL)
4090 goto onError;
4091 /* need more space? (at least enough for what we
4092 have+the replacement+the rest of the string (starting
4093 at the new input position), so we won't have to check space
4094 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004095 requiredsize = *outpos;
4096 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4097 goto overflow;
4098 requiredsize += repwlen;
4099 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4100 goto overflow;
4101 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004102 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004103 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004104 requiredsize = 2*outsize;
4105 if (unicode_resize(output, requiredsize) < 0)
4106 goto onError;
4107 }
4108 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4109 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004110 *endinpos = newpos;
4111 *inptr = *input + newpos;
4112
4113 /* we made it! */
4114 Py_XDECREF(restuple);
4115 return 0;
4116
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004117 overflow:
4118 PyErr_SetString(PyExc_OverflowError,
4119 "decoded result is too long for a Python string");
4120
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004121 onError:
4122 Py_XDECREF(restuple);
4123 return -1;
4124}
4125#endif /* HAVE_MBCS */
4126
4127static int
4128unicode_decode_call_errorhandler_writer(
4129 const char *errors, PyObject **errorHandler,
4130 const char *encoding, const char *reason,
4131 const char **input, const char **inend, Py_ssize_t *startinpos,
4132 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4133 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4134{
4135 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4136
4137 PyObject *restuple = NULL;
4138 PyObject *repunicode = NULL;
4139 Py_ssize_t insize;
4140 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004141 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004142 PyObject *inputobj = NULL;
4143
4144 if (*errorHandler == NULL) {
4145 *errorHandler = PyCodec_LookupError(errors);
4146 if (*errorHandler == NULL)
4147 goto onError;
4148 }
4149
4150 make_decode_exception(exceptionObject,
4151 encoding,
4152 *input, *inend - *input,
4153 *startinpos, *endinpos,
4154 reason);
4155 if (*exceptionObject == NULL)
4156 goto onError;
4157
4158 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4159 if (restuple == NULL)
4160 goto onError;
4161 if (!PyTuple_Check(restuple)) {
4162 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4163 goto onError;
4164 }
4165 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004166 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004167
4168 /* Copy back the bytes variables, which might have been modified by the
4169 callback */
4170 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4171 if (!inputobj)
4172 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004173 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004174 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004175 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004176 *input = PyBytes_AS_STRING(inputobj);
4177 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004178 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004179 /* we can DECREF safely, as the exception has another reference,
4180 so the object won't go away. */
4181 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004182
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004183 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004184 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004185 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004186 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004187 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004188 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004189
Victor Stinner8f674cc2013-04-17 23:02:17 +02004190 if (PyUnicode_READY(repunicode) < 0)
4191 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004192 replen = PyUnicode_GET_LENGTH(repunicode);
4193 writer->min_length += replen;
4194 if (replen > 1)
Victor Stinner8f674cc2013-04-17 23:02:17 +02004195 writer->overallocate = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004196 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004197 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004199 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004200 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004201
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004202 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004203 Py_XDECREF(restuple);
4204 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004205
Benjamin Peterson29060642009-01-31 22:14:21 +00004206 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004207 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004208 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209}
4210
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004211/* --- UTF-7 Codec -------------------------------------------------------- */
4212
Antoine Pitrou244651a2009-05-04 18:56:13 +00004213/* See RFC2152 for details. We encode conservatively and decode liberally. */
4214
4215/* Three simple macros defining base-64. */
4216
4217/* Is c a base-64 character? */
4218
4219#define IS_BASE64(c) \
4220 (((c) >= 'A' && (c) <= 'Z') || \
4221 ((c) >= 'a' && (c) <= 'z') || \
4222 ((c) >= '0' && (c) <= '9') || \
4223 (c) == '+' || (c) == '/')
4224
4225/* given that c is a base-64 character, what is its base-64 value? */
4226
4227#define FROM_BASE64(c) \
4228 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4229 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4230 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4231 (c) == '+' ? 62 : 63)
4232
4233/* What is the base-64 character of the bottom 6 bits of n? */
4234
4235#define TO_BASE64(n) \
4236 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4237
4238/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4239 * decoded as itself. We are permissive on decoding; the only ASCII
4240 * byte not decoding to itself is the + which begins a base64
4241 * string. */
4242
4243#define DECODE_DIRECT(c) \
4244 ((c) <= 127 && (c) != '+')
4245
4246/* The UTF-7 encoder treats ASCII characters differently according to
4247 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4248 * the above). See RFC2152. This array identifies these different
4249 * sets:
4250 * 0 : "Set D"
4251 * alphanumeric and '(),-./:?
4252 * 1 : "Set O"
4253 * !"#$%&*;<=>@[]^_`{|}
4254 * 2 : "whitespace"
4255 * ht nl cr sp
4256 * 3 : special (must be base64 encoded)
4257 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4258 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259
Tim Petersced69f82003-09-16 20:30:58 +00004260static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261char utf7_category[128] = {
4262/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4263 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4264/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4265 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4266/* sp ! " # $ % & ' ( ) * + , - . / */
4267 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4268/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4270/* @ A B C D E F G H I J K L M N O */
4271 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4272/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4273 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4274/* ` a b c d e f g h i j k l m n o */
4275 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4276/* p q r s t u v w x y z { | } ~ del */
4277 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004278};
4279
Antoine Pitrou244651a2009-05-04 18:56:13 +00004280/* ENCODE_DIRECT: this character should be encoded as itself. The
4281 * answer depends on whether we are encoding set O as itself, and also
4282 * on whether we are encoding whitespace as itself. RFC2152 makes it
4283 * clear that the answers to these questions vary between
4284 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004285
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286#define ENCODE_DIRECT(c, directO, directWS) \
4287 ((c) < 128 && (c) > 0 && \
4288 ((utf7_category[(c)] == 0) || \
4289 (directWS && (utf7_category[(c)] == 2)) || \
4290 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004291
Alexander Belopolsky40018472011-02-26 01:02:56 +00004292PyObject *
4293PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004294 Py_ssize_t size,
4295 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004296{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004297 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4298}
4299
Antoine Pitrou244651a2009-05-04 18:56:13 +00004300/* The decoder. The only state we preserve is our read position,
4301 * i.e. how many characters we have consumed. So if we end in the
4302 * middle of a shift sequence we have to back off the read position
4303 * and the output to the beginning of the sequence, otherwise we lose
4304 * all the shift state (seen bits, number of bits seen, high
4305 * surrogate). */
4306
Alexander Belopolsky40018472011-02-26 01:02:56 +00004307PyObject *
4308PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004309 Py_ssize_t size,
4310 const char *errors,
4311 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004312{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004313 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004314 Py_ssize_t startinpos;
4315 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004317 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318 const char *errmsg = "";
4319 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 unsigned int base64bits = 0;
4322 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004323 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004324 PyObject *errorHandler = NULL;
4325 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004326
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004327 if (size == 0) {
4328 if (consumed)
4329 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004330 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004331 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004332
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004333 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004334 _PyUnicodeWriter_Init(&writer);
4335 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004336
4337 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004338 e = s + size;
4339
4340 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004341 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004342 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004343 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004344
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345 if (inShift) { /* in a base-64 section */
4346 if (IS_BASE64(ch)) { /* consume a base-64 character */
4347 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4348 base64bits += 6;
4349 s++;
4350 if (base64bits >= 16) {
4351 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004352 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353 base64bits -= 16;
4354 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004355 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004356 if (surrogate) {
4357 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004358 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4359 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004360 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004361 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004363 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 }
4365 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004366 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004367 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 }
4370 }
Victor Stinner551ac952011-11-29 22:58:13 +01004371 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372 /* first surrogate */
4373 surrogate = outCh;
4374 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004376 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004377 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 }
4379 }
4380 }
4381 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382 inShift = 0;
4383 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004384 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004385 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004386 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004387 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 if (base64bits > 0) { /* left-over bits */
4390 if (base64bits >= 6) {
4391 /* We've seen at least one base-64 character */
4392 errmsg = "partial character in shift sequence";
4393 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395 else {
4396 /* Some bits remain; they should be zero */
4397 if (base64buffer != 0) {
4398 errmsg = "non-zero padding bits in shift sequence";
4399 goto utf7Error;
4400 }
4401 }
4402 }
4403 if (ch != '-') {
4404 /* '-' is absorbed; other terminating
4405 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004406 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004407 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
4410 }
4411 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004412 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004413 s++; /* consume '+' */
4414 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004416 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004417 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 }
4419 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004420 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004422 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004423 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424 }
4425 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004427 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004428 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004429 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 else {
4432 startinpos = s-starts;
4433 s++;
4434 errmsg = "unexpected special character";
4435 goto utf7Error;
4436 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004437 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004439 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004440 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 errors, &errorHandler,
4442 "utf7", errmsg,
4443 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004444 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004445 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004446 }
4447
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448 /* end of string */
4449
4450 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4451 /* if we're in an inconsistent state, that's an error */
4452 if (surrogate ||
4453 (base64bits >= 6) ||
4454 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004456 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 errors, &errorHandler,
4458 "utf7", "unterminated shift sequence",
4459 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004460 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 goto onError;
4462 if (s < e)
4463 goto restart;
4464 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004466
4467 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004468 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004469 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004470 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004471 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004472 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004473 writer.kind, writer.data, shiftOutStart);
4474 Py_XDECREF(errorHandler);
4475 Py_XDECREF(exc);
4476 _PyUnicodeWriter_Dealloc(&writer);
4477 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004478 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004479 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 }
4481 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004482 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004484 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004486 Py_XDECREF(errorHandler);
4487 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004488 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004489
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004491 Py_XDECREF(errorHandler);
4492 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004493 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 return NULL;
4495}
4496
4497
Alexander Belopolsky40018472011-02-26 01:02:56 +00004498PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004499_PyUnicode_EncodeUTF7(PyObject *str,
4500 int base64SetO,
4501 int base64WhiteSpace,
4502 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504 int kind;
4505 void *data;
4506 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004507 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004508 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004509 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004510 unsigned int base64bits = 0;
4511 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004512 char * out;
4513 char * start;
4514
Benjamin Petersonbac79492012-01-14 13:34:47 -05004515 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 return NULL;
4517 kind = PyUnicode_KIND(str);
4518 data = PyUnicode_DATA(str);
4519 len = PyUnicode_GET_LENGTH(str);
4520
4521 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004522 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004523
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004524 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004525 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004526 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004527 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004528 if (v == NULL)
4529 return NULL;
4530
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004531 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004532 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004533 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 if (inShift) {
4536 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4537 /* shifting out */
4538 if (base64bits) { /* output remaining bits */
4539 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4540 base64buffer = 0;
4541 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004542 }
4543 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004544 /* Characters not in the BASE64 set implicitly unshift the sequence
4545 so no '-' is required, except if the character is itself a '-' */
4546 if (IS_BASE64(ch) || ch == '-') {
4547 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004548 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 *out++ = (char) ch;
4550 }
4551 else {
4552 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004553 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004555 else { /* not in a shift sequence */
4556 if (ch == '+') {
4557 *out++ = '+';
4558 *out++ = '-';
4559 }
4560 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4561 *out++ = (char) ch;
4562 }
4563 else {
4564 *out++ = '+';
4565 inShift = 1;
4566 goto encode_char;
4567 }
4568 }
4569 continue;
4570encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004571 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004572 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004573
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 /* code first surrogate */
4575 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004576 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 while (base64bits >= 6) {
4578 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4579 base64bits -= 6;
4580 }
4581 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004582 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004583 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 base64bits += 16;
4585 base64buffer = (base64buffer << 16) | ch;
4586 while (base64bits >= 6) {
4587 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4588 base64bits -= 6;
4589 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004590 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004591 if (base64bits)
4592 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4593 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004594 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004595 if (_PyBytes_Resize(&v, out - start) < 0)
4596 return NULL;
4597 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004599PyObject *
4600PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4601 Py_ssize_t size,
4602 int base64SetO,
4603 int base64WhiteSpace,
4604 const char *errors)
4605{
4606 PyObject *result;
4607 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4608 if (tmp == NULL)
4609 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004610 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004611 base64WhiteSpace, errors);
4612 Py_DECREF(tmp);
4613 return result;
4614}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616#undef IS_BASE64
4617#undef FROM_BASE64
4618#undef TO_BASE64
4619#undef DECODE_DIRECT
4620#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621
Guido van Rossumd57fd912000-03-10 22:53:23 +00004622/* --- UTF-8 Codec -------------------------------------------------------- */
4623
Alexander Belopolsky40018472011-02-26 01:02:56 +00004624PyObject *
4625PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004626 Py_ssize_t size,
4627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004628{
Walter Dörwald69652032004-09-07 20:24:22 +00004629 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4630}
4631
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004632#include "stringlib/asciilib.h"
4633#include "stringlib/codecs.h"
4634#include "stringlib/undef.h"
4635
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004636#include "stringlib/ucs1lib.h"
4637#include "stringlib/codecs.h"
4638#include "stringlib/undef.h"
4639
4640#include "stringlib/ucs2lib.h"
4641#include "stringlib/codecs.h"
4642#include "stringlib/undef.h"
4643
4644#include "stringlib/ucs4lib.h"
4645#include "stringlib/codecs.h"
4646#include "stringlib/undef.h"
4647
Antoine Pitrouab868312009-01-10 15:40:25 +00004648/* Mask to quickly check whether a C 'long' contains a
4649 non-ASCII, UTF8-encoded char. */
4650#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004651# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004652#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004653# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004654#else
4655# error C 'long' size should be either 4 or 8!
4656#endif
4657
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004658static Py_ssize_t
4659ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004660{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004662 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004663
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004664 /*
4665 * Issue #17237: m68k is a bit different from most architectures in
4666 * that objects do not use "natural alignment" - for example, int and
4667 * long are only aligned at 2-byte boundaries. Therefore the assert()
4668 * won't work; also, tests have shown that skipping the "optimised
4669 * version" will even speed up m68k.
4670 */
4671#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004672#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004673 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4674 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675 /* Fast path, see in STRINGLIB(utf8_decode) for
4676 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004677 /* Help allocation */
4678 const char *_p = p;
4679 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 while (_p < aligned_end) {
4681 unsigned long value = *(const unsigned long *) _p;
4682 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004683 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004684 *((unsigned long *)q) = value;
4685 _p += SIZEOF_LONG;
4686 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004687 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004688 p = _p;
4689 while (p < end) {
4690 if ((unsigned char)*p & 0x80)
4691 break;
4692 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004693 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004696#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004697#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 while (p < end) {
4699 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4700 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004701 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004702 /* Help allocation */
4703 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004704 while (_p < aligned_end) {
4705 unsigned long value = *(unsigned long *) _p;
4706 if (value & ASCII_CHAR_MASK)
4707 break;
4708 _p += SIZEOF_LONG;
4709 }
4710 p = _p;
4711 if (_p == end)
4712 break;
4713 }
4714 if ((unsigned char)*p & 0x80)
4715 break;
4716 ++p;
4717 }
4718 memcpy(dest, start, p - start);
4719 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004720}
Antoine Pitrouab868312009-01-10 15:40:25 +00004721
Victor Stinner785938e2011-12-11 20:09:03 +01004722PyObject *
4723PyUnicode_DecodeUTF8Stateful(const char *s,
4724 Py_ssize_t size,
4725 const char *errors,
4726 Py_ssize_t *consumed)
4727{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004729 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731
4732 Py_ssize_t startinpos;
4733 Py_ssize_t endinpos;
4734 const char *errmsg = "";
4735 PyObject *errorHandler = NULL;
4736 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004737
4738 if (size == 0) {
4739 if (consumed)
4740 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004741 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004742 }
4743
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004744 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4745 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004746 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004747 *consumed = 1;
4748 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004749 }
4750
Victor Stinner8f674cc2013-04-17 23:02:17 +02004751 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004752 writer.min_length = size;
4753 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004755
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004756 writer.pos = ascii_decode(s, end, writer.data);
4757 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 while (s < end) {
4759 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004760 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004761 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 if (PyUnicode_IS_ASCII(writer.buffer))
4763 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004765 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004767 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 } else {
4769 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004770 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 }
4772
4773 switch (ch) {
4774 case 0:
4775 if (s == end || consumed)
4776 goto End;
4777 errmsg = "unexpected end of data";
4778 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004779 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004780 break;
4781 case 1:
4782 errmsg = "invalid start byte";
4783 startinpos = s - starts;
4784 endinpos = startinpos + 1;
4785 break;
4786 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004787 case 3:
4788 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789 errmsg = "invalid continuation byte";
4790 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004791 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 break;
4793 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004794 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 goto onError;
4796 continue;
4797 }
4798
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004799 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 errors, &errorHandler,
4801 "utf-8", errmsg,
4802 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004803 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004804 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004805 }
4806
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004808 if (consumed)
4809 *consumed = s - starts;
4810
4811 Py_XDECREF(errorHandler);
4812 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004813 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814
4815onError:
4816 Py_XDECREF(errorHandler);
4817 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004818 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004819 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004820}
4821
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822#ifdef __APPLE__
4823
4824/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004825 used to decode the command line arguments on Mac OS X.
4826
4827 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004828 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004829
4830wchar_t*
4831_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4832{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004833 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004834 wchar_t *unicode;
4835 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836
4837 /* Note: size will always be longer than the resulting Unicode
4838 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004839 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004840 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004841 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004842 if (!unicode)
4843 return NULL;
4844
4845 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004846 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004847 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004848 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004849 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004850#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004852#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004853 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004854#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004855 if (ch > 0xFF) {
4856#if SIZEOF_WCHAR_T == 4
4857 assert(0);
4858#else
4859 assert(Py_UNICODE_IS_SURROGATE(ch));
4860 /* compute and append the two surrogates: */
4861 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4862 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4863#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 else {
4866 if (!ch && s == e)
4867 break;
4868 /* surrogateescape */
4869 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4870 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004871 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004873 return unicode;
4874}
4875
4876#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004878/* Primary internal function which creates utf8 encoded bytes objects.
4879
4880 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004881 and allocate exactly as much space needed at the end. Else allocate the
4882 maximum possible needed (4 result bytes per Unicode character), and return
4883 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004884*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004885PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004886_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004887{
Victor Stinner6099a032011-12-18 14:22:26 +01004888 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004889 void *data;
4890 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004892 if (!PyUnicode_Check(unicode)) {
4893 PyErr_BadArgument();
4894 return NULL;
4895 }
4896
4897 if (PyUnicode_READY(unicode) == -1)
4898 return NULL;
4899
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004900 if (PyUnicode_UTF8(unicode))
4901 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4902 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004903
4904 kind = PyUnicode_KIND(unicode);
4905 data = PyUnicode_DATA(unicode);
4906 size = PyUnicode_GET_LENGTH(unicode);
4907
Benjamin Petersonead6b532011-12-20 17:23:42 -06004908 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004909 default:
4910 assert(0);
4911 case PyUnicode_1BYTE_KIND:
4912 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4913 assert(!PyUnicode_IS_ASCII(unicode));
4914 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4915 case PyUnicode_2BYTE_KIND:
4916 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4917 case PyUnicode_4BYTE_KIND:
4918 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004919 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004920}
4921
Alexander Belopolsky40018472011-02-26 01:02:56 +00004922PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004923PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4924 Py_ssize_t size,
4925 const char *errors)
4926{
4927 PyObject *v, *unicode;
4928
4929 unicode = PyUnicode_FromUnicode(s, size);
4930 if (unicode == NULL)
4931 return NULL;
4932 v = _PyUnicode_AsUTF8String(unicode, errors);
4933 Py_DECREF(unicode);
4934 return v;
4935}
4936
4937PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004938PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004940 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004941}
4942
Walter Dörwald41980ca2007-08-16 21:55:45 +00004943/* --- UTF-32 Codec ------------------------------------------------------- */
4944
4945PyObject *
4946PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004947 Py_ssize_t size,
4948 const char *errors,
4949 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950{
4951 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4952}
4953
4954PyObject *
4955PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004956 Py_ssize_t size,
4957 const char *errors,
4958 int *byteorder,
4959 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004960{
4961 const char *starts = s;
4962 Py_ssize_t startinpos;
4963 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004964 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004965 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004966 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004967 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969 PyObject *errorHandler = NULL;
4970 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004971
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 q = (unsigned char *)s;
4973 e = q + size;
4974
4975 if (byteorder)
4976 bo = *byteorder;
4977
4978 /* Check for BOM marks (U+FEFF) in the input and adjust current
4979 byte order setting accordingly. In native mode, the leading BOM
4980 mark is skipped, in all other modes, it is copied to the output
4981 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004982 if (bo == 0 && size >= 4) {
4983 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4984 if (bom == 0x0000FEFF) {
4985 bo = -1;
4986 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004988 else if (bom == 0xFFFE0000) {
4989 bo = 1;
4990 q += 4;
4991 }
4992 if (byteorder)
4993 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994 }
4995
Victor Stinnere64322e2012-10-30 23:12:47 +01004996 if (q == e) {
4997 if (consumed)
4998 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004999 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000 }
5001
Victor Stinnere64322e2012-10-30 23:12:47 +01005002#ifdef WORDS_BIGENDIAN
5003 le = bo < 0;
5004#else
5005 le = bo <= 0;
5006#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005007 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005008
Victor Stinner8f674cc2013-04-17 23:02:17 +02005009 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005010 writer.min_length = (e - q + 3) / 4;
5011 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005012 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005013
Victor Stinnere64322e2012-10-30 23:12:47 +01005014 while (1) {
5015 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005016 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005017
Victor Stinnere64322e2012-10-30 23:12:47 +01005018 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005019 enum PyUnicode_Kind kind = writer.kind;
5020 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005022 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 if (le) {
5024 do {
5025 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5026 if (ch > maxch)
5027 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005028 if (kind != PyUnicode_1BYTE_KIND &&
5029 Py_UNICODE_IS_SURROGATE(ch))
5030 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005031 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005032 q += 4;
5033 } while (q <= last);
5034 }
5035 else {
5036 do {
5037 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5038 if (ch > maxch)
5039 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005040 if (kind != PyUnicode_1BYTE_KIND &&
5041 Py_UNICODE_IS_SURROGATE(ch))
5042 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005043 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005044 q += 4;
5045 } while (q <= last);
5046 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005047 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 }
5049
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005050 if (Py_UNICODE_IS_SURROGATE(ch)) {
5051 errmsg = "codepoint in surrogate code point range(0xd800, 0xe000)";
5052 startinpos = ((const char *)q) - starts;
5053 endinpos = startinpos + 4;
5054 }
5055 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005056 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005057 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005058 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005059 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005060 startinpos = ((const char *)q) - starts;
5061 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 else {
5064 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005065 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005066 goto onError;
5067 q += 4;
5068 continue;
5069 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005070 errmsg = "codepoint not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005071 startinpos = ((const char *)q) - starts;
5072 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005073 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005074
5075 /* The remaining input chars are ignored if the callback
5076 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005077 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005079 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005080 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005081 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005082 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 }
5084
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005086 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005087
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 Py_XDECREF(errorHandler);
5089 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005090 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091
Benjamin Peterson29060642009-01-31 22:14:21 +00005092 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005093 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094 Py_XDECREF(errorHandler);
5095 Py_XDECREF(exc);
5096 return NULL;
5097}
5098
5099PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100_PyUnicode_EncodeUTF32(PyObject *str,
5101 const char *errors,
5102 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 int kind;
5105 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005106 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005107 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005108 unsigned char *p;
5109 Py_ssize_t nsize, i;
5110 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005111#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005112 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005114 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005116 const char *encoding;
5117 PyObject *errorHandler = NULL;
5118 PyObject *exc = NULL;
5119 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005120
Serhiy Storchaka30793282014-01-04 22:44:01 +02005121#define STORECHAR(CH) \
5122 do { \
5123 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5124 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5125 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5126 p[iorder[0]] = (CH) & 0xff; \
5127 p += 4; \
5128 } while(0)
5129
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005130 if (!PyUnicode_Check(str)) {
5131 PyErr_BadArgument();
5132 return NULL;
5133 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005134 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005135 return NULL;
5136 kind = PyUnicode_KIND(str);
5137 data = PyUnicode_DATA(str);
5138 len = PyUnicode_GET_LENGTH(str);
5139
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005140 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 if (nsize > PY_SSIZE_T_MAX / 4)
5142 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005143 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144 if (v == NULL)
5145 return NULL;
5146
Serhiy Storchaka30793282014-01-04 22:44:01 +02005147 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005148 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005149 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005150 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005151 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005152
Serhiy Storchaka30793282014-01-04 22:44:01 +02005153 if (byteorder == -1) {
5154 /* force LE */
5155 iorder[0] = 0;
5156 iorder[1] = 1;
5157 iorder[2] = 2;
5158 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005159 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005160 }
5161 else if (byteorder == 1) {
5162 /* force BE */
5163 iorder[0] = 3;
5164 iorder[1] = 2;
5165 iorder[2] = 1;
5166 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005167 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005168 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005169 else
5170 encoding = "utf-32";
5171
5172 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005173 for (i = 0; i < len; i++)
5174 STORECHAR(PyUnicode_READ(kind, data, i));
5175 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005176 }
5177
Serhiy Storchaka30793282014-01-04 22:44:01 +02005178 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005179 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005180 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5181 i++;
5182 assert(ch <= MAX_UNICODE);
5183 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5184 STORECHAR(ch);
5185 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005186 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005187
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005188 rep = unicode_encode_call_errorhandler(
5189 errors, &errorHandler,
5190 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005191 str, &exc, i-1, i, &i);
5192
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (!rep)
5194 goto error;
5195
5196 if (PyBytes_Check(rep)) {
5197 repsize = PyBytes_GET_SIZE(rep);
5198 if (repsize & 3) {
5199 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005200 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 "surrogates not allowed");
5202 goto error;
5203 }
5204 moreunits = repsize / 4;
5205 }
5206 else {
5207 assert(PyUnicode_Check(rep));
5208 if (PyUnicode_READY(rep) < 0)
5209 goto error;
5210 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5211 if (!PyUnicode_IS_ASCII(rep)) {
5212 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005213 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 "surrogates not allowed");
5215 goto error;
5216 }
5217 }
5218
5219 /* four bytes are reserved for each surrogate */
5220 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005221 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005222 Py_ssize_t morebytes = 4 * (moreunits - 1);
5223 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5224 /* integer overflow */
5225 PyErr_NoMemory();
5226 goto error;
5227 }
5228 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5229 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005230 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005231 }
5232
5233 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005234 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5235 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005237 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005238 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005239 repdata = PyUnicode_1BYTE_DATA(rep);
5240 while (repsize--) {
5241 Py_UCS4 ch = *repdata++;
5242 STORECHAR(ch);
5243 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005244 }
5245
5246 Py_CLEAR(rep);
5247 }
5248
5249 /* Cut back to size actually needed. This is necessary for, for example,
5250 encoding of a string containing isolated surrogates and the 'ignore'
5251 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005252 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005253 if (nsize != PyBytes_GET_SIZE(v))
5254 _PyBytes_Resize(&v, nsize);
5255 Py_XDECREF(errorHandler);
5256 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005257 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005258 error:
5259 Py_XDECREF(rep);
5260 Py_XDECREF(errorHandler);
5261 Py_XDECREF(exc);
5262 Py_XDECREF(v);
5263 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005264#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005265}
5266
Alexander Belopolsky40018472011-02-26 01:02:56 +00005267PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005268PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5269 Py_ssize_t size,
5270 const char *errors,
5271 int byteorder)
5272{
5273 PyObject *result;
5274 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5275 if (tmp == NULL)
5276 return NULL;
5277 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5278 Py_DECREF(tmp);
5279 return result;
5280}
5281
5282PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005283PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284{
Victor Stinnerb960b342011-11-20 19:12:52 +01005285 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005286}
5287
Guido van Rossumd57fd912000-03-10 22:53:23 +00005288/* --- UTF-16 Codec ------------------------------------------------------- */
5289
Tim Peters772747b2001-08-09 22:21:55 +00005290PyObject *
5291PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005292 Py_ssize_t size,
5293 const char *errors,
5294 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005295{
Walter Dörwald69652032004-09-07 20:24:22 +00005296 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5297}
5298
5299PyObject *
5300PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005301 Py_ssize_t size,
5302 const char *errors,
5303 int *byteorder,
5304 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005306 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005307 Py_ssize_t startinpos;
5308 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005309 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005310 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005311 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005313 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005314 PyObject *errorHandler = NULL;
5315 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005317
Tim Peters772747b2001-08-09 22:21:55 +00005318 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005320
5321 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005322 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005323
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005324 /* Check for BOM marks (U+FEFF) in the input and adjust current
5325 byte order setting accordingly. In native mode, the leading BOM
5326 mark is skipped, in all other modes, it is copied to the output
5327 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005328 if (bo == 0 && size >= 2) {
5329 const Py_UCS4 bom = (q[1] << 8) | q[0];
5330 if (bom == 0xFEFF) {
5331 q += 2;
5332 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 else if (bom == 0xFFFE) {
5335 q += 2;
5336 bo = 1;
5337 }
5338 if (byteorder)
5339 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005340 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005341
Antoine Pitrou63065d72012-05-15 23:48:04 +02005342 if (q == e) {
5343 if (consumed)
5344 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005345 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005346 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005347
Christian Heimes743e0cd2012-10-17 23:52:17 +02005348#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005349 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005350 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005351#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005352 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005353 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005354#endif
Tim Peters772747b2001-08-09 22:21:55 +00005355
Antoine Pitrou63065d72012-05-15 23:48:04 +02005356 /* Note: size will always be longer than the resulting Unicode
5357 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005358 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005359 writer.min_length = (e - q + 1) / 2;
5360 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005361 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005362
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 while (1) {
5364 Py_UCS4 ch = 0;
5365 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005368 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 else
5373 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005374 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005375 native_ordering);
5376 } else if (kind == PyUnicode_2BYTE_KIND) {
5377 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005378 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005379 native_ordering);
5380 } else {
5381 assert(kind == PyUnicode_4BYTE_KIND);
5382 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005383 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005384 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005386 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005387
Antoine Pitrou63065d72012-05-15 23:48:04 +02005388 switch (ch)
5389 {
5390 case 0:
5391 /* remaining byte at the end? (size should be even) */
5392 if (q == e || consumed)
5393 goto End;
5394 errmsg = "truncated data";
5395 startinpos = ((const char *)q) - starts;
5396 endinpos = ((const char *)e) - starts;
5397 break;
5398 /* The remaining input chars are ignored if the callback
5399 chooses to skip the input */
5400 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005401 q -= 2;
5402 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005403 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005404 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005405 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005406 endinpos = ((const char *)e) - starts;
5407 break;
5408 case 2:
5409 errmsg = "illegal encoding";
5410 startinpos = ((const char *)q) - 2 - starts;
5411 endinpos = startinpos + 2;
5412 break;
5413 case 3:
5414 errmsg = "illegal UTF-16 surrogate";
5415 startinpos = ((const char *)q) - 4 - starts;
5416 endinpos = startinpos + 2;
5417 break;
5418 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005419 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005420 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 continue;
5422 }
5423
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005424 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005425 errors,
5426 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005427 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005428 &starts,
5429 (const char **)&e,
5430 &startinpos,
5431 &endinpos,
5432 &exc,
5433 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005434 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005435 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 }
5437
Antoine Pitrou63065d72012-05-15 23:48:04 +02005438End:
Walter Dörwald69652032004-09-07 20:24:22 +00005439 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005440 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005441
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005442 Py_XDECREF(errorHandler);
5443 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005444 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445
Benjamin Peterson29060642009-01-31 22:14:21 +00005446 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005447 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005448 Py_XDECREF(errorHandler);
5449 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005450 return NULL;
5451}
5452
Tim Peters772747b2001-08-09 22:21:55 +00005453PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454_PyUnicode_EncodeUTF16(PyObject *str,
5455 const char *errors,
5456 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005457{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005458 enum PyUnicode_Kind kind;
5459 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005460 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005461 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005462 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005464#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005466#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005467 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005468#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 const char *encoding;
5470 Py_ssize_t nsize, pos;
5471 PyObject *errorHandler = NULL;
5472 PyObject *exc = NULL;
5473 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005474
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005475 if (!PyUnicode_Check(str)) {
5476 PyErr_BadArgument();
5477 return NULL;
5478 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005479 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005480 return NULL;
5481 kind = PyUnicode_KIND(str);
5482 data = PyUnicode_DATA(str);
5483 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005484
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005485 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005486 if (kind == PyUnicode_4BYTE_KIND) {
5487 const Py_UCS4 *in = (const Py_UCS4 *)data;
5488 const Py_UCS4 *end = in + len;
5489 while (in < end)
5490 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005491 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005492 }
5493 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005494 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005495 nsize = len + pairs + (byteorder == 0);
5496 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497 if (v == NULL)
5498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005500 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005501 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005502 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005503 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005504 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005505 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005506 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005507
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005508 if (kind == PyUnicode_1BYTE_KIND) {
5509 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5510 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005511 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005512
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005513 if (byteorder < 0)
5514 encoding = "utf-16-le";
5515 else if (byteorder > 0)
5516 encoding = "utf-16-be";
5517 else
5518 encoding = "utf-16";
5519
5520 pos = 0;
5521 while (pos < len) {
5522 Py_ssize_t repsize, moreunits;
5523
5524 if (kind == PyUnicode_2BYTE_KIND) {
5525 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5526 &out, native_ordering);
5527 }
5528 else {
5529 assert(kind == PyUnicode_4BYTE_KIND);
5530 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5531 &out, native_ordering);
5532 }
5533 if (pos == len)
5534 break;
5535
5536 rep = unicode_encode_call_errorhandler(
5537 errors, &errorHandler,
5538 encoding, "surrogates not allowed",
5539 str, &exc, pos, pos + 1, &pos);
5540 if (!rep)
5541 goto error;
5542
5543 if (PyBytes_Check(rep)) {
5544 repsize = PyBytes_GET_SIZE(rep);
5545 if (repsize & 1) {
5546 raise_encode_exception(&exc, encoding,
5547 str, pos - 1, pos,
5548 "surrogates not allowed");
5549 goto error;
5550 }
5551 moreunits = repsize / 2;
5552 }
5553 else {
5554 assert(PyUnicode_Check(rep));
5555 if (PyUnicode_READY(rep) < 0)
5556 goto error;
5557 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5558 if (!PyUnicode_IS_ASCII(rep)) {
5559 raise_encode_exception(&exc, encoding,
5560 str, pos - 1, pos,
5561 "surrogates not allowed");
5562 goto error;
5563 }
5564 }
5565
5566 /* two bytes are reserved for each surrogate */
5567 if (moreunits > 1) {
5568 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5569 Py_ssize_t morebytes = 2 * (moreunits - 1);
5570 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5571 /* integer overflow */
5572 PyErr_NoMemory();
5573 goto error;
5574 }
5575 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5576 goto error;
5577 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5578 }
5579
5580 if (PyBytes_Check(rep)) {
5581 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5582 out += moreunits;
5583 } else /* rep is unicode */ {
5584 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5585 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5586 &out, native_ordering);
5587 }
5588
5589 Py_CLEAR(rep);
5590 }
5591
5592 /* Cut back to size actually needed. This is necessary for, for example,
5593 encoding of a string containing isolated surrogates and the 'ignore' handler
5594 is used. */
5595 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5596 if (nsize != PyBytes_GET_SIZE(v))
5597 _PyBytes_Resize(&v, nsize);
5598 Py_XDECREF(errorHandler);
5599 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005600 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005601 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005602 error:
5603 Py_XDECREF(rep);
5604 Py_XDECREF(errorHandler);
5605 Py_XDECREF(exc);
5606 Py_XDECREF(v);
5607 return NULL;
5608#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005609}
5610
Alexander Belopolsky40018472011-02-26 01:02:56 +00005611PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005612PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5613 Py_ssize_t size,
5614 const char *errors,
5615 int byteorder)
5616{
5617 PyObject *result;
5618 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5619 if (tmp == NULL)
5620 return NULL;
5621 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5622 Py_DECREF(tmp);
5623 return result;
5624}
5625
5626PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005627PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005629 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630}
5631
5632/* --- Unicode Escape Codec ----------------------------------------------- */
5633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5635 if all the escapes in the string make it still a valid ASCII string.
5636 Returns -1 if any escapes were found which cause the string to
5637 pop out of ASCII range. Otherwise returns the length of the
5638 required buffer to hold the string.
5639 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005640static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5642{
5643 const unsigned char *p = (const unsigned char *)s;
5644 const unsigned char *end = p + size;
5645 Py_ssize_t length = 0;
5646
5647 if (size < 0)
5648 return -1;
5649
5650 for (; p < end; ++p) {
5651 if (*p > 127) {
5652 /* Non-ASCII */
5653 return -1;
5654 }
5655 else if (*p != '\\') {
5656 /* Normal character */
5657 ++length;
5658 }
5659 else {
5660 /* Backslash-escape, check next char */
5661 ++p;
5662 /* Escape sequence reaches till end of string or
5663 non-ASCII follow-up. */
5664 if (p >= end || *p > 127)
5665 return -1;
5666 switch (*p) {
5667 case '\n':
5668 /* backslash + \n result in zero characters */
5669 break;
5670 case '\\': case '\'': case '\"':
5671 case 'b': case 'f': case 't':
5672 case 'n': case 'r': case 'v': case 'a':
5673 ++length;
5674 break;
5675 case '0': case '1': case '2': case '3':
5676 case '4': case '5': case '6': case '7':
5677 case 'x': case 'u': case 'U': case 'N':
5678 /* these do not guarantee ASCII characters */
5679 return -1;
5680 default:
5681 /* count the backslash + the other character */
5682 length += 2;
5683 }
5684 }
5685 }
5686 return length;
5687}
5688
Fredrik Lundh06d12682001-01-24 07:59:11 +00005689static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005690
Alexander Belopolsky40018472011-02-26 01:02:56 +00005691PyObject *
5692PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005693 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005694 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005696 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005697 Py_ssize_t startinpos;
5698 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005699 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005701 char* message;
5702 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005703 PyObject *errorHandler = NULL;
5704 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005706
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005707 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005708 if (len == 0)
5709 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710
5711 /* After length_of_escaped_ascii_string() there are two alternatives,
5712 either the string is pure ASCII with named escapes like \n, etc.
5713 and we determined it's exact size (common case)
5714 or it contains \x, \u, ... escape sequences. then we create a
5715 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005716 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005717 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005718 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005719 }
5720 else {
5721 /* Escaped strings will always be longer than the resulting
5722 Unicode string, so we start with size here and then reduce the
5723 length after conversion to the true value.
5724 (but if the error callback returns a long replacement string
5725 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005726 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005727 }
5728
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005730 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005732
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 while (s < end) {
5734 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005735 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005736 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737
5738 /* Non-escape characters are interpreted as Unicode ordinals */
5739 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005740 x = (unsigned char)*s;
5741 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005742 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 continue;
5745 }
5746
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005747 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005748 /* \ - Escapes */
5749 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005750 c = *s++;
5751 if (s > end)
5752 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005753
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005754 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755
Benjamin Peterson29060642009-01-31 22:14:21 +00005756 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005757#define WRITECHAR(ch) \
5758 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005759 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005760 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005761 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005762
Guido van Rossumd57fd912000-03-10 22:53:23 +00005763 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005764 case '\\': WRITECHAR('\\'); break;
5765 case '\'': WRITECHAR('\''); break;
5766 case '\"': WRITECHAR('\"'); break;
5767 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005768 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005769 case 'f': WRITECHAR('\014'); break;
5770 case 't': WRITECHAR('\t'); break;
5771 case 'n': WRITECHAR('\n'); break;
5772 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005774 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005775 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005776 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005777
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005779 case '0': case '1': case '2': case '3':
5780 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005781 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005782 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005783 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005784 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005785 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005786 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005787 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788 break;
5789
Benjamin Peterson29060642009-01-31 22:14:21 +00005790 /* hex escapes */
5791 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 digits = 2;
5794 message = "truncated \\xXX escape";
5795 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005798 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 digits = 4;
5800 message = "truncated \\uXXXX escape";
5801 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005802
Benjamin Peterson29060642009-01-31 22:14:21 +00005803 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005805 digits = 8;
5806 message = "truncated \\UXXXXXXXX escape";
5807 hexescape:
5808 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005809 if (end - s < digits) {
5810 /* count only hex digits */
5811 for (; s < end; ++s) {
5812 c = (unsigned char)*s;
5813 if (!Py_ISXDIGIT(c))
5814 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005815 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005816 goto error;
5817 }
5818 for (; digits--; ++s) {
5819 c = (unsigned char)*s;
5820 if (!Py_ISXDIGIT(c))
5821 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005822 chr = (chr<<4) & ~0xF;
5823 if (c >= '0' && c <= '9')
5824 chr += c - '0';
5825 else if (c >= 'a' && c <= 'f')
5826 chr += 10 + c - 'a';
5827 else
5828 chr += 10 + c - 'A';
5829 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005830 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005831 /* _decoding_error will have already written into the
5832 target buffer. */
5833 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005835 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005836 message = "illegal Unicode character";
5837 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005838 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005839 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005840 break;
5841
Benjamin Peterson29060642009-01-31 22:14:21 +00005842 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 case 'N':
5844 message = "malformed \\N character escape";
5845 if (ucnhash_CAPI == NULL) {
5846 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5848 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005849 if (ucnhash_CAPI == NULL)
5850 goto ucnhashError;
5851 }
5852 if (*s == '{') {
5853 const char *start = s+1;
5854 /* look for the closing brace */
5855 while (*s != '}' && s < end)
5856 s++;
5857 if (s > start && s < end && *s == '}') {
5858 /* found a name. look it up in the unicode database */
5859 message = "unknown Unicode character name";
5860 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005861 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005862 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005863 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005864 goto store;
5865 }
5866 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005867 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005868
5869 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005871 message = "\\ at end of string";
5872 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005873 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 }
5875 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005877 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005878 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005879 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005881 continue;
5882
5883 error:
5884 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005885 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005886 errors, &errorHandler,
5887 "unicodeescape", message,
5888 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005889 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005890 goto onError;
5891 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005892 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005893#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005894
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005895 Py_XDECREF(errorHandler);
5896 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005897 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005898
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005900 PyErr_SetString(
5901 PyExc_UnicodeError,
5902 "\\N escapes not supported (can't load unicodedata module)"
5903 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005904 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 Py_XDECREF(errorHandler);
5906 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005907 return NULL;
5908
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005910 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 Py_XDECREF(errorHandler);
5912 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 return NULL;
5914}
5915
5916/* Return a Unicode-Escape string version of the Unicode object.
5917
5918 If quotes is true, the string is enclosed in u"" or u'' quotes as
5919 appropriate.
5920
5921*/
5922
Alexander Belopolsky40018472011-02-26 01:02:56 +00005923PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005924PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005926 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005927 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 int kind;
5930 void *data;
5931 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932
Ezio Melottie7f90372012-10-05 03:33:31 +03005933 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005934 escape.
5935
Ezio Melottie7f90372012-10-05 03:33:31 +03005936 For UCS1 strings it's '\xxx', 4 bytes per source character.
5937 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5938 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005939 */
5940
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005941 if (!PyUnicode_Check(unicode)) {
5942 PyErr_BadArgument();
5943 return NULL;
5944 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005945 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005946 return NULL;
5947 len = PyUnicode_GET_LENGTH(unicode);
5948 kind = PyUnicode_KIND(unicode);
5949 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005950 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005951 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5952 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5953 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5954 }
5955
5956 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 return PyBytes_FromStringAndSize(NULL, 0);
5958
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005959 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005960 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005961
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005962 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005964 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966 if (repr == NULL)
5967 return NULL;
5968
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005969 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005970
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005971 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005972 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005973
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 /* Escape backslashes */
5975 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 *p++ = '\\';
5977 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005978 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005979 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005980
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005981 /* Map 21-bit characters to '\U00xxxxxx' */
5982 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005983 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005984 *p++ = '\\';
5985 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005986 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5987 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5989 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5993 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005994 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005995 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005996
Guido van Rossumd57fd912000-03-10 22:53:23 +00005997 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005998 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 *p++ = '\\';
6000 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006001 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6002 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6003 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6004 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006005 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006006
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006007 /* Map special whitespace to '\t', \n', '\r' */
6008 else if (ch == '\t') {
6009 *p++ = '\\';
6010 *p++ = 't';
6011 }
6012 else if (ch == '\n') {
6013 *p++ = '\\';
6014 *p++ = 'n';
6015 }
6016 else if (ch == '\r') {
6017 *p++ = '\\';
6018 *p++ = 'r';
6019 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006020
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006021 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006022 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006023 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006024 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006025 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6026 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006027 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006028
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 /* Copy everything else as-is */
6030 else
6031 *p++ = (char) ch;
6032 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006034 assert(p - PyBytes_AS_STRING(repr) > 0);
6035 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6036 return NULL;
6037 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038}
6039
Alexander Belopolsky40018472011-02-26 01:02:56 +00006040PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006041PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6042 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044 PyObject *result;
6045 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6046 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006048 result = PyUnicode_AsUnicodeEscapeString(tmp);
6049 Py_DECREF(tmp);
6050 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051}
6052
6053/* --- Raw Unicode Escape Codec ------------------------------------------- */
6054
Alexander Belopolsky40018472011-02-26 01:02:56 +00006055PyObject *
6056PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006057 Py_ssize_t size,
6058 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006061 Py_ssize_t startinpos;
6062 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006063 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 const char *end;
6065 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006066 PyObject *errorHandler = NULL;
6067 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006068
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006069 if (size == 0)
6070 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006071
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 /* Escaped strings will always be longer than the resulting
6073 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006074 length after conversion to the true value. (But decoding error
6075 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006076 _PyUnicodeWriter_Init(&writer);
6077 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006078
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079 end = s + size;
6080 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 unsigned char c;
6082 Py_UCS4 x;
6083 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006084 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 /* Non-escape characters are interpreted as Unicode ordinals */
6087 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006088 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006089 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006090 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006092 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 startinpos = s-starts;
6094
6095 /* \u-escapes are only interpreted iff the number of leading
6096 backslashes if odd */
6097 bs = s;
6098 for (;s < end;) {
6099 if (*s != '\\')
6100 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006102 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006103 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006104 }
6105 if (((s - bs) & 1) == 0 ||
6106 s >= end ||
6107 (*s != 'u' && *s != 'U')) {
6108 continue;
6109 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006110 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 count = *s=='u' ? 4 : 8;
6112 s++;
6113
6114 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 for (x = 0, i = 0; i < count; ++i, ++s) {
6116 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006117 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006119 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 errors, &errorHandler,
6121 "rawunicodeescape", "truncated \\uXXXX",
6122 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006123 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 goto onError;
6125 goto nextByte;
6126 }
6127 x = (x<<4) & ~0xF;
6128 if (c >= '0' && c <= '9')
6129 x += c - '0';
6130 else if (c >= 'a' && c <= 'f')
6131 x += 10 + c - 'a';
6132 else
6133 x += 10 + c - 'A';
6134 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006135 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006136 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006137 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006138 }
6139 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006140 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006141 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006142 errors, &errorHandler,
6143 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006145 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006147 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006148 nextByte:
6149 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006151 Py_XDECREF(errorHandler);
6152 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006153 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006154
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006156 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006157 Py_XDECREF(errorHandler);
6158 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006159 return NULL;
6160}
6161
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006162
Alexander Belopolsky40018472011-02-26 01:02:56 +00006163PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006166 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167 char *p;
6168 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006169 Py_ssize_t expandsize, pos;
6170 int kind;
6171 void *data;
6172 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006174 if (!PyUnicode_Check(unicode)) {
6175 PyErr_BadArgument();
6176 return NULL;
6177 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006178 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 return NULL;
6180 kind = PyUnicode_KIND(unicode);
6181 data = PyUnicode_DATA(unicode);
6182 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006183 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6184 bytes, and 1 byte characters 4. */
6185 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006186
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 if (repr == NULL)
6192 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006194 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006195
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006196 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006197 for (pos = 0; pos < len; pos++) {
6198 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006199 /* Map 32-bit characters to '\Uxxxxxxxx' */
6200 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006201 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006202 *p++ = '\\';
6203 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006204 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6205 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6207 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6208 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6209 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6211 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006212 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006213 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215 *p++ = '\\';
6216 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006217 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6218 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6219 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6220 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006222 /* Copy everything else as-is */
6223 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224 *p++ = (char) ch;
6225 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006226
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006227 assert(p > q);
6228 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006229 return NULL;
6230 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231}
6232
Alexander Belopolsky40018472011-02-26 01:02:56 +00006233PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006234PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6235 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237 PyObject *result;
6238 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6239 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006240 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006241 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6242 Py_DECREF(tmp);
6243 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244}
6245
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246/* --- Unicode Internal Codec ------------------------------------------- */
6247
Alexander Belopolsky40018472011-02-26 01:02:56 +00006248PyObject *
6249_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006250 Py_ssize_t size,
6251 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006252{
6253 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006254 Py_ssize_t startinpos;
6255 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006256 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006257 const char *end;
6258 const char *reason;
6259 PyObject *errorHandler = NULL;
6260 PyObject *exc = NULL;
6261
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006262 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006263 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006264 1))
6265 return NULL;
6266
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006267 if (size == 0)
6268 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006269
Victor Stinner8f674cc2013-04-17 23:02:17 +02006270 _PyUnicodeWriter_Init(&writer);
6271 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6272 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006274 }
6275 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006276
Victor Stinner8f674cc2013-04-17 23:02:17 +02006277 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006279 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006280 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006281 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006282 endinpos = end-starts;
6283 reason = "truncated input";
6284 goto error;
6285 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006286 /* We copy the raw representation one byte at a time because the
6287 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006288 ((char *) &uch)[0] = s[0];
6289 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006290#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006291 ((char *) &uch)[2] = s[2];
6292 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006293#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006294 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 /* We have to sanity check the raw data, otherwise doom looms for
6297 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006298 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006299 endinpos = s - starts + Py_UNICODE_SIZE;
6300 reason = "illegal code point (> 0x10FFFF)";
6301 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006302 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006303#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006304 s += Py_UNICODE_SIZE;
6305#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006306 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006307 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006308 Py_UNICODE uch2;
6309 ((char *) &uch2)[0] = s[0];
6310 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006311 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006312 {
Victor Stinner551ac952011-11-29 22:58:13 +01006313 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006314 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006315 }
6316 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006317#endif
6318
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006319 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006320 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006321 continue;
6322
6323 error:
6324 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006325 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006326 errors, &errorHandler,
6327 "unicode_internal", reason,
6328 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006329 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006330 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006331 }
6332
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006333 Py_XDECREF(errorHandler);
6334 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006335 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336
Benjamin Peterson29060642009-01-31 22:14:21 +00006337 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006338 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 Py_XDECREF(errorHandler);
6340 Py_XDECREF(exc);
6341 return NULL;
6342}
6343
Guido van Rossumd57fd912000-03-10 22:53:23 +00006344/* --- Latin-1 Codec ------------------------------------------------------ */
6345
Alexander Belopolsky40018472011-02-26 01:02:56 +00006346PyObject *
6347PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006348 Py_ssize_t size,
6349 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006351 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006352 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353}
6354
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006356static void
6357make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006358 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006359 PyObject *unicode,
6360 Py_ssize_t startpos, Py_ssize_t endpos,
6361 const char *reason)
6362{
6363 if (*exceptionObject == NULL) {
6364 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006365 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006366 encoding, unicode, startpos, endpos, reason);
6367 }
6368 else {
6369 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6370 goto onError;
6371 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6372 goto onError;
6373 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6374 goto onError;
6375 return;
6376 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006377 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006378 }
6379}
6380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006381/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006382static void
6383raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006384 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006385 PyObject *unicode,
6386 Py_ssize_t startpos, Py_ssize_t endpos,
6387 const char *reason)
6388{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006389 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006390 encoding, unicode, startpos, endpos, reason);
6391 if (*exceptionObject != NULL)
6392 PyCodec_StrictErrors(*exceptionObject);
6393}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394
6395/* error handling callback helper:
6396 build arguments, call the callback and check the arguments,
6397 put the result into newpos and return the replacement string, which
6398 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006399static PyObject *
6400unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006401 PyObject **errorHandler,
6402 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006404 Py_ssize_t startpos, Py_ssize_t endpos,
6405 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006407 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006408 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 PyObject *restuple;
6410 PyObject *resunicode;
6411
6412 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 }
6417
Benjamin Petersonbac79492012-01-14 13:34:47 -05006418 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 return NULL;
6420 len = PyUnicode_GET_LENGTH(unicode);
6421
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006422 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006423 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426
6427 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006432 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 Py_DECREF(restuple);
6434 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006436 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 &resunicode, newpos)) {
6438 Py_DECREF(restuple);
6439 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006441 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6442 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6443 Py_DECREF(restuple);
6444 return NULL;
6445 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 *newpos = len + *newpos;
6448 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006449 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 Py_DECREF(restuple);
6451 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006452 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453 Py_INCREF(resunicode);
6454 Py_DECREF(restuple);
6455 return resunicode;
6456}
6457
Alexander Belopolsky40018472011-02-26 01:02:56 +00006458static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006460 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006461 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 /* input state */
6464 Py_ssize_t pos=0, size;
6465 int kind;
6466 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 /* output object */
6468 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 /* pointer into the output */
6470 char *str;
6471 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006472 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006473 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6474 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006475 PyObject *errorHandler = NULL;
6476 PyObject *exc = NULL;
6477 /* the following variable is used for caching string comparisons
6478 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6479 int known_errorHandler = -1;
6480
Benjamin Petersonbac79492012-01-14 13:34:47 -05006481 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 return NULL;
6483 size = PyUnicode_GET_LENGTH(unicode);
6484 kind = PyUnicode_KIND(unicode);
6485 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 /* allocate enough for a simple encoding without
6487 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006488 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006489 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006490 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006492 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006493 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 ressize = size;
6495
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 while (pos < size) {
6497 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006498
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 /* can we encode this? */
6500 if (c<limit) {
6501 /* no overflow check, because we know that the space is enough */
6502 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006504 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 Py_ssize_t requiredsize;
6507 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 Py_ssize_t collstart = pos;
6511 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006513 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 ++collend;
6515 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6516 if (known_errorHandler==-1) {
6517 if ((errors==NULL) || (!strcmp(errors, "strict")))
6518 known_errorHandler = 1;
6519 else if (!strcmp(errors, "replace"))
6520 known_errorHandler = 2;
6521 else if (!strcmp(errors, "ignore"))
6522 known_errorHandler = 3;
6523 else if (!strcmp(errors, "xmlcharrefreplace"))
6524 known_errorHandler = 4;
6525 else
6526 known_errorHandler = 0;
6527 }
6528 switch (known_errorHandler) {
6529 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006530 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 goto onError;
6532 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006533 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 *str++ = '?'; /* fall through */
6535 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 break;
6538 case 4: /* xmlcharrefreplace */
6539 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006540 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006541 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006542 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006544 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006546 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006548 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006550 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006551 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006552 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006554 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006555 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006556 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006557 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006558 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006559 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006560 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006561 if (requiredsize > PY_SSIZE_T_MAX - incr)
6562 goto overflow;
6563 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006565 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6566 goto overflow;
6567 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006568 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006569 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 requiredsize = 2*ressize;
6571 if (_PyBytes_Resize(&res, requiredsize))
6572 goto onError;
6573 str = PyBytes_AS_STRING(res) + respos;
6574 ressize = requiredsize;
6575 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006576 /* generate replacement */
6577 for (i = collstart; i < collend; ++i) {
6578 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006579 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006581 break;
6582 default:
6583 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 encoding, reason, unicode, &exc,
6585 collstart, collend, &newpos);
6586 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006587 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006589 if (PyBytes_Check(repunicode)) {
6590 /* Directly copy bytes result to output. */
6591 repsize = PyBytes_Size(repunicode);
6592 if (repsize > 1) {
6593 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006594 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006595 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6596 Py_DECREF(repunicode);
6597 goto overflow;
6598 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006599 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6600 Py_DECREF(repunicode);
6601 goto onError;
6602 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006603 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006604 ressize += repsize-1;
6605 }
6606 memcpy(str, PyBytes_AsString(repunicode), repsize);
6607 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006609 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006610 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006611 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 /* need more space? (at least enough for what we
6613 have+the replacement+the rest of the string, so
6614 we won't have to check space for encodable characters) */
6615 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006616 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006617 requiredsize = respos;
6618 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6619 goto overflow;
6620 requiredsize += repsize;
6621 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6622 goto overflow;
6623 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006625 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 requiredsize = 2*ressize;
6627 if (_PyBytes_Resize(&res, requiredsize)) {
6628 Py_DECREF(repunicode);
6629 goto onError;
6630 }
6631 str = PyBytes_AS_STRING(res) + respos;
6632 ressize = requiredsize;
6633 }
6634 /* check if there is anything unencodable in the replacement
6635 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 for (i = 0; repsize-->0; ++i, ++str) {
6637 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006639 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006640 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 Py_DECREF(repunicode);
6642 goto onError;
6643 }
6644 *str = (char)c;
6645 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006647 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006648 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006649 }
6650 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006651 /* Resize if we allocated to much */
6652 size = str - PyBytes_AS_STRING(res);
6653 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006654 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006655 if (_PyBytes_Resize(&res, size) < 0)
6656 goto onError;
6657 }
6658
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 Py_XDECREF(errorHandler);
6660 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006661 return res;
6662
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006663 overflow:
6664 PyErr_SetString(PyExc_OverflowError,
6665 "encoded result is too long for a Python string");
6666
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006667 onError:
6668 Py_XDECREF(res);
6669 Py_XDECREF(errorHandler);
6670 Py_XDECREF(exc);
6671 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672}
6673
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006675PyObject *
6676PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006677 Py_ssize_t size,
6678 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006679{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 PyObject *result;
6681 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6682 if (unicode == NULL)
6683 return NULL;
6684 result = unicode_encode_ucs1(unicode, errors, 256);
6685 Py_DECREF(unicode);
6686 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006687}
6688
Alexander Belopolsky40018472011-02-26 01:02:56 +00006689PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006690_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691{
6692 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006693 PyErr_BadArgument();
6694 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006696 if (PyUnicode_READY(unicode) == -1)
6697 return NULL;
6698 /* Fast path: if it is a one-byte string, construct
6699 bytes object directly. */
6700 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6701 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6702 PyUnicode_GET_LENGTH(unicode));
6703 /* Non-Latin-1 characters present. Defer to above function to
6704 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006705 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006706}
6707
6708PyObject*
6709PyUnicode_AsLatin1String(PyObject *unicode)
6710{
6711 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712}
6713
6714/* --- 7-bit ASCII Codec -------------------------------------------------- */
6715
Alexander Belopolsky40018472011-02-26 01:02:56 +00006716PyObject *
6717PyUnicode_DecodeASCII(const char *s,
6718 Py_ssize_t size,
6719 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006722 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006723 int kind;
6724 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006725 Py_ssize_t startinpos;
6726 Py_ssize_t endinpos;
6727 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006728 const char *e;
6729 PyObject *errorHandler = NULL;
6730 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006731
Guido van Rossumd57fd912000-03-10 22:53:23 +00006732 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006733 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006734
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006736 if (size == 1 && (unsigned char)s[0] < 128)
6737 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006738
Victor Stinner8f674cc2013-04-17 23:02:17 +02006739 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006740 writer.min_length = size;
6741 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006742 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006743
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006745 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006746 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006747 writer.pos = outpos;
6748 if (writer.pos == size)
6749 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006750
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006751 s += writer.pos;
6752 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006753 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006754 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006756 PyUnicode_WRITE(kind, data, writer.pos, c);
6757 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 ++s;
6759 }
6760 else {
6761 startinpos = s-starts;
6762 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006763 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 errors, &errorHandler,
6765 "ascii", "ordinal not in range(128)",
6766 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006767 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006769 kind = writer.kind;
6770 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006773 Py_XDECREF(errorHandler);
6774 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006775 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006776
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006778 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006779 Py_XDECREF(errorHandler);
6780 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006781 return NULL;
6782}
6783
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006785PyObject *
6786PyUnicode_EncodeASCII(const Py_UNICODE *p,
6787 Py_ssize_t size,
6788 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006789{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 PyObject *result;
6791 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6792 if (unicode == NULL)
6793 return NULL;
6794 result = unicode_encode_ucs1(unicode, errors, 128);
6795 Py_DECREF(unicode);
6796 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006797}
6798
Alexander Belopolsky40018472011-02-26 01:02:56 +00006799PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006800_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801{
6802 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 PyErr_BadArgument();
6804 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006806 if (PyUnicode_READY(unicode) == -1)
6807 return NULL;
6808 /* Fast path: if it is an ASCII-only string, construct bytes object
6809 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006810 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006811 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6812 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006813 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814}
6815
6816PyObject *
6817PyUnicode_AsASCIIString(PyObject *unicode)
6818{
6819 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006820}
6821
Victor Stinner99b95382011-07-04 14:23:54 +02006822#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006823
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006824/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006825
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006826#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827#define NEED_RETRY
6828#endif
6829
Victor Stinner3a50e702011-10-18 21:21:00 +02006830#ifndef WC_ERR_INVALID_CHARS
6831# define WC_ERR_INVALID_CHARS 0x0080
6832#endif
6833
6834static char*
6835code_page_name(UINT code_page, PyObject **obj)
6836{
6837 *obj = NULL;
6838 if (code_page == CP_ACP)
6839 return "mbcs";
6840 if (code_page == CP_UTF7)
6841 return "CP_UTF7";
6842 if (code_page == CP_UTF8)
6843 return "CP_UTF8";
6844
6845 *obj = PyBytes_FromFormat("cp%u", code_page);
6846 if (*obj == NULL)
6847 return NULL;
6848 return PyBytes_AS_STRING(*obj);
6849}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006850
Alexander Belopolsky40018472011-02-26 01:02:56 +00006851static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006852is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006853{
6854 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 if (!IsDBCSLeadByteEx(code_page, *curr))
6858 return 0;
6859
6860 prev = CharPrevExA(code_page, s, curr, 0);
6861 if (prev == curr)
6862 return 1;
6863 /* FIXME: This code is limited to "true" double-byte encodings,
6864 as it assumes an incomplete character consists of a single
6865 byte. */
6866 if (curr - prev == 2)
6867 return 1;
6868 if (!IsDBCSLeadByteEx(code_page, *prev))
6869 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006870 return 0;
6871}
6872
Victor Stinner3a50e702011-10-18 21:21:00 +02006873static DWORD
6874decode_code_page_flags(UINT code_page)
6875{
6876 if (code_page == CP_UTF7) {
6877 /* The CP_UTF7 decoder only supports flags=0 */
6878 return 0;
6879 }
6880 else
6881 return MB_ERR_INVALID_CHARS;
6882}
6883
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006884/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 * Decode a byte string from a Windows code page into unicode object in strict
6886 * mode.
6887 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006888 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6889 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006890 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006891static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006892decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006893 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006894 const char *in,
6895 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006896{
Victor Stinner3a50e702011-10-18 21:21:00 +02006897 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006898 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006899 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006900
6901 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 assert(insize > 0);
6903 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6904 if (outsize <= 0)
6905 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906
6907 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006909 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006910 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006911 if (*v == NULL)
6912 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006914 }
6915 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006916 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006917 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006918 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006921 }
6922
6923 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006924 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6925 if (outsize <= 0)
6926 goto error;
6927 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006928
Victor Stinner3a50e702011-10-18 21:21:00 +02006929error:
6930 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6931 return -2;
6932 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006933 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934}
6935
Victor Stinner3a50e702011-10-18 21:21:00 +02006936/*
6937 * Decode a byte string from a code page into unicode object with an error
6938 * handler.
6939 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006940 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006941 * UnicodeDecodeError exception and returns -1 on error.
6942 */
6943static int
6944decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006945 PyObject **v,
6946 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006947 const char *errors)
6948{
6949 const char *startin = in;
6950 const char *endin = in + size;
6951 const DWORD flags = decode_code_page_flags(code_page);
6952 /* Ideally, we should get reason from FormatMessage. This is the Windows
6953 2000 English version of the message. */
6954 const char *reason = "No mapping for the Unicode character exists "
6955 "in the target code page.";
6956 /* each step cannot decode more than 1 character, but a character can be
6957 represented as a surrogate pair */
6958 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006959 int insize;
6960 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 PyObject *errorHandler = NULL;
6962 PyObject *exc = NULL;
6963 PyObject *encoding_obj = NULL;
6964 char *encoding;
6965 DWORD err;
6966 int ret = -1;
6967
6968 assert(size > 0);
6969
6970 encoding = code_page_name(code_page, &encoding_obj);
6971 if (encoding == NULL)
6972 return -1;
6973
6974 if (errors == NULL || strcmp(errors, "strict") == 0) {
6975 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6976 UnicodeDecodeError. */
6977 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6978 if (exc != NULL) {
6979 PyCodec_StrictErrors(exc);
6980 Py_CLEAR(exc);
6981 }
6982 goto error;
6983 }
6984
6985 if (*v == NULL) {
6986 /* Create unicode object */
6987 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6988 PyErr_NoMemory();
6989 goto error;
6990 }
Victor Stinnerab595942011-12-17 04:59:06 +01006991 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006992 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006993 if (*v == NULL)
6994 goto error;
6995 startout = PyUnicode_AS_UNICODE(*v);
6996 }
6997 else {
6998 /* Extend unicode object */
6999 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7000 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7001 PyErr_NoMemory();
7002 goto error;
7003 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007004 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007005 goto error;
7006 startout = PyUnicode_AS_UNICODE(*v) + n;
7007 }
7008
7009 /* Decode the byte string character per character */
7010 out = startout;
7011 while (in < endin)
7012 {
7013 /* Decode a character */
7014 insize = 1;
7015 do
7016 {
7017 outsize = MultiByteToWideChar(code_page, flags,
7018 in, insize,
7019 buffer, Py_ARRAY_LENGTH(buffer));
7020 if (outsize > 0)
7021 break;
7022 err = GetLastError();
7023 if (err != ERROR_NO_UNICODE_TRANSLATION
7024 && err != ERROR_INSUFFICIENT_BUFFER)
7025 {
7026 PyErr_SetFromWindowsErr(0);
7027 goto error;
7028 }
7029 insize++;
7030 }
7031 /* 4=maximum length of a UTF-8 sequence */
7032 while (insize <= 4 && (in + insize) <= endin);
7033
7034 if (outsize <= 0) {
7035 Py_ssize_t startinpos, endinpos, outpos;
7036
7037 startinpos = in - startin;
7038 endinpos = startinpos + 1;
7039 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007040 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007041 errors, &errorHandler,
7042 encoding, reason,
7043 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007044 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007045 {
7046 goto error;
7047 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007048 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007049 }
7050 else {
7051 in += insize;
7052 memcpy(out, buffer, outsize * sizeof(wchar_t));
7053 out += outsize;
7054 }
7055 }
7056
7057 /* write a NUL character at the end */
7058 *out = 0;
7059
7060 /* Extend unicode object */
7061 outsize = out - startout;
7062 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007063 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007065 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007066
7067error:
7068 Py_XDECREF(encoding_obj);
7069 Py_XDECREF(errorHandler);
7070 Py_XDECREF(exc);
7071 return ret;
7072}
7073
Victor Stinner3a50e702011-10-18 21:21:00 +02007074static PyObject *
7075decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 const char *s, Py_ssize_t size,
7077 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078{
Victor Stinner76a31a62011-11-04 00:05:13 +01007079 PyObject *v = NULL;
7080 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
Victor Stinner3a50e702011-10-18 21:21:00 +02007082 if (code_page < 0) {
7083 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7084 return NULL;
7085 }
7086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007088 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
Victor Stinner76a31a62011-11-04 00:05:13 +01007090 do
7091 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007093 if (size > INT_MAX) {
7094 chunk_size = INT_MAX;
7095 final = 0;
7096 done = 0;
7097 }
7098 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007099#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007100 {
7101 chunk_size = (int)size;
7102 final = (consumed == NULL);
7103 done = 1;
7104 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105
Victor Stinner76a31a62011-11-04 00:05:13 +01007106 /* Skip trailing lead-byte unless 'final' is set */
7107 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7108 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109
Victor Stinner76a31a62011-11-04 00:05:13 +01007110 if (chunk_size == 0 && done) {
7111 if (v != NULL)
7112 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007113 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007114 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007115
Victor Stinner76a31a62011-11-04 00:05:13 +01007116
7117 converted = decode_code_page_strict(code_page, &v,
7118 s, chunk_size);
7119 if (converted == -2)
7120 converted = decode_code_page_errors(code_page, &v,
7121 s, chunk_size,
7122 errors);
7123 assert(converted != 0);
7124
7125 if (converted < 0) {
7126 Py_XDECREF(v);
7127 return NULL;
7128 }
7129
7130 if (consumed)
7131 *consumed += converted;
7132
7133 s += converted;
7134 size -= converted;
7135 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007136
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007137 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007138}
7139
Alexander Belopolsky40018472011-02-26 01:02:56 +00007140PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007141PyUnicode_DecodeCodePageStateful(int code_page,
7142 const char *s,
7143 Py_ssize_t size,
7144 const char *errors,
7145 Py_ssize_t *consumed)
7146{
7147 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7148}
7149
7150PyObject *
7151PyUnicode_DecodeMBCSStateful(const char *s,
7152 Py_ssize_t size,
7153 const char *errors,
7154 Py_ssize_t *consumed)
7155{
7156 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7157}
7158
7159PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007160PyUnicode_DecodeMBCS(const char *s,
7161 Py_ssize_t size,
7162 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007163{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007164 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7165}
7166
Victor Stinner3a50e702011-10-18 21:21:00 +02007167static DWORD
7168encode_code_page_flags(UINT code_page, const char *errors)
7169{
7170 if (code_page == CP_UTF8) {
7171 if (winver.dwMajorVersion >= 6)
7172 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7173 and later */
7174 return WC_ERR_INVALID_CHARS;
7175 else
7176 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7177 return 0;
7178 }
7179 else if (code_page == CP_UTF7) {
7180 /* CP_UTF7 only supports flags=0 */
7181 return 0;
7182 }
7183 else {
7184 if (errors != NULL && strcmp(errors, "replace") == 0)
7185 return 0;
7186 else
7187 return WC_NO_BEST_FIT_CHARS;
7188 }
7189}
7190
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 * Encode a Unicode string to a Windows code page into a byte string in strict
7193 * mode.
7194 *
7195 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007196 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007198static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007199encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007200 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202{
Victor Stinner554f3f02010-06-16 23:33:54 +00007203 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 BOOL *pusedDefaultChar = &usedDefaultChar;
7205 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007206 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007207 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007208 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 const DWORD flags = encode_code_page_flags(code_page, NULL);
7210 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 /* Create a substring so that we can get the UTF-16 representation
7212 of just the slice under consideration. */
7213 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214
Martin v. Löwis3d325192011-11-04 18:23:06 +01007215 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007216
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007218 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007220 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007221
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 substring = PyUnicode_Substring(unicode, offset, offset+len);
7223 if (substring == NULL)
7224 return -1;
7225 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7226 if (p == NULL) {
7227 Py_DECREF(substring);
7228 return -1;
7229 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007230 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007231
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007232 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007234 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007235 NULL, 0,
7236 NULL, pusedDefaultChar);
7237 if (outsize <= 0)
7238 goto error;
7239 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007240 if (pusedDefaultChar && *pusedDefaultChar) {
7241 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007243 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007244
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007246 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 if (*outbytes == NULL) {
7249 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007250 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007253 }
7254 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007255 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 const Py_ssize_t n = PyBytes_Size(*outbytes);
7257 if (outsize > PY_SSIZE_T_MAX - n) {
7258 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007259 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007262 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7263 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007265 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267 }
7268
7269 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007271 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 out, outsize,
7273 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007274 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 if (outsize <= 0)
7276 goto error;
7277 if (pusedDefaultChar && *pusedDefaultChar)
7278 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007280
Victor Stinner3a50e702011-10-18 21:21:00 +02007281error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007282 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7284 return -2;
7285 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007286 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007287}
7288
Victor Stinner3a50e702011-10-18 21:21:00 +02007289/*
7290 * Encode a Unicode string to a Windows code page into a byte string using a
7291 * error handler.
7292 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007293 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007294 * -1 on other error.
7295 */
7296static int
7297encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007298 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007299 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007300{
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007302 Py_ssize_t pos = unicode_offset;
7303 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 /* Ideally, we should get reason from FormatMessage. This is the Windows
7305 2000 English version of the message. */
7306 const char *reason = "invalid character";
7307 /* 4=maximum length of a UTF-8 sequence */
7308 char buffer[4];
7309 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7310 Py_ssize_t outsize;
7311 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 PyObject *errorHandler = NULL;
7313 PyObject *exc = NULL;
7314 PyObject *encoding_obj = NULL;
7315 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007316 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007317 PyObject *rep;
7318 int ret = -1;
7319
7320 assert(insize > 0);
7321
7322 encoding = code_page_name(code_page, &encoding_obj);
7323 if (encoding == NULL)
7324 return -1;
7325
7326 if (errors == NULL || strcmp(errors, "strict") == 0) {
7327 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7328 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007329 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 if (exc != NULL) {
7331 PyCodec_StrictErrors(exc);
7332 Py_DECREF(exc);
7333 }
7334 Py_XDECREF(encoding_obj);
7335 return -1;
7336 }
7337
7338 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7339 pusedDefaultChar = &usedDefaultChar;
7340 else
7341 pusedDefaultChar = NULL;
7342
7343 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7344 PyErr_NoMemory();
7345 goto error;
7346 }
7347 outsize = insize * Py_ARRAY_LENGTH(buffer);
7348
7349 if (*outbytes == NULL) {
7350 /* Create string object */
7351 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7352 if (*outbytes == NULL)
7353 goto error;
7354 out = PyBytes_AS_STRING(*outbytes);
7355 }
7356 else {
7357 /* Extend string object */
7358 Py_ssize_t n = PyBytes_Size(*outbytes);
7359 if (n > PY_SSIZE_T_MAX - outsize) {
7360 PyErr_NoMemory();
7361 goto error;
7362 }
7363 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7364 goto error;
7365 out = PyBytes_AS_STRING(*outbytes) + n;
7366 }
7367
7368 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007369 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007371 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7372 wchar_t chars[2];
7373 int charsize;
7374 if (ch < 0x10000) {
7375 chars[0] = (wchar_t)ch;
7376 charsize = 1;
7377 }
7378 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007379 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7380 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007381 charsize = 2;
7382 }
7383
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 buffer, Py_ARRAY_LENGTH(buffer),
7387 NULL, pusedDefaultChar);
7388 if (outsize > 0) {
7389 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7390 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007391 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 memcpy(out, buffer, outsize);
7393 out += outsize;
7394 continue;
7395 }
7396 }
7397 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7398 PyErr_SetFromWindowsErr(0);
7399 goto error;
7400 }
7401
Victor Stinner3a50e702011-10-18 21:21:00 +02007402 rep = unicode_encode_call_errorhandler(
7403 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007404 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 if (rep == NULL)
7407 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007408 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007409
7410 if (PyBytes_Check(rep)) {
7411 outsize = PyBytes_GET_SIZE(rep);
7412 if (outsize != 1) {
7413 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7414 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7415 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7416 Py_DECREF(rep);
7417 goto error;
7418 }
7419 out = PyBytes_AS_STRING(*outbytes) + offset;
7420 }
7421 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7422 out += outsize;
7423 }
7424 else {
7425 Py_ssize_t i;
7426 enum PyUnicode_Kind kind;
7427 void *data;
7428
Benjamin Petersonbac79492012-01-14 13:34:47 -05007429 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 Py_DECREF(rep);
7431 goto error;
7432 }
7433
7434 outsize = PyUnicode_GET_LENGTH(rep);
7435 if (outsize != 1) {
7436 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7437 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7438 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7439 Py_DECREF(rep);
7440 goto error;
7441 }
7442 out = PyBytes_AS_STRING(*outbytes) + offset;
7443 }
7444 kind = PyUnicode_KIND(rep);
7445 data = PyUnicode_DATA(rep);
7446 for (i=0; i < outsize; i++) {
7447 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7448 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007449 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007450 encoding, unicode,
7451 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 "unable to encode error handler result to ASCII");
7453 Py_DECREF(rep);
7454 goto error;
7455 }
7456 *out = (unsigned char)ch;
7457 out++;
7458 }
7459 }
7460 Py_DECREF(rep);
7461 }
7462 /* write a NUL byte */
7463 *out = 0;
7464 outsize = out - PyBytes_AS_STRING(*outbytes);
7465 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7466 if (_PyBytes_Resize(outbytes, outsize) < 0)
7467 goto error;
7468 ret = 0;
7469
7470error:
7471 Py_XDECREF(encoding_obj);
7472 Py_XDECREF(errorHandler);
7473 Py_XDECREF(exc);
7474 return ret;
7475}
7476
Victor Stinner3a50e702011-10-18 21:21:00 +02007477static PyObject *
7478encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007479 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 const char *errors)
7481{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007482 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007484 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007485 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007486
Benjamin Petersonbac79492012-01-14 13:34:47 -05007487 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007488 return NULL;
7489 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007490
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 if (code_page < 0) {
7492 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7493 return NULL;
7494 }
7495
Martin v. Löwis3d325192011-11-04 18:23:06 +01007496 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007497 return PyBytes_FromStringAndSize(NULL, 0);
7498
Victor Stinner7581cef2011-11-03 22:32:33 +01007499 offset = 0;
7500 do
7501 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007502#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007503 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 chunks. */
7505 if (len > INT_MAX/2) {
7506 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007507 done = 0;
7508 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007509 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007511 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007512 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007513 done = 1;
7514 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007515
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007517 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007518 errors);
7519 if (ret == -2)
7520 ret = encode_code_page_errors(code_page, &outbytes,
7521 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007522 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007523 if (ret < 0) {
7524 Py_XDECREF(outbytes);
7525 return NULL;
7526 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007527
Victor Stinner7581cef2011-11-03 22:32:33 +01007528 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007529 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007530 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007531
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 return outbytes;
7533}
7534
7535PyObject *
7536PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7537 Py_ssize_t size,
7538 const char *errors)
7539{
Victor Stinner7581cef2011-11-03 22:32:33 +01007540 PyObject *unicode, *res;
7541 unicode = PyUnicode_FromUnicode(p, size);
7542 if (unicode == NULL)
7543 return NULL;
7544 res = encode_code_page(CP_ACP, unicode, errors);
7545 Py_DECREF(unicode);
7546 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007547}
7548
7549PyObject *
7550PyUnicode_EncodeCodePage(int code_page,
7551 PyObject *unicode,
7552 const char *errors)
7553{
Victor Stinner7581cef2011-11-03 22:32:33 +01007554 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007555}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007556
Alexander Belopolsky40018472011-02-26 01:02:56 +00007557PyObject *
7558PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007559{
7560 if (!PyUnicode_Check(unicode)) {
7561 PyErr_BadArgument();
7562 return NULL;
7563 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007564 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007565}
7566
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007567#undef NEED_RETRY
7568
Victor Stinner99b95382011-07-04 14:23:54 +02007569#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007570
Guido van Rossumd57fd912000-03-10 22:53:23 +00007571/* --- Character Mapping Codec -------------------------------------------- */
7572
Victor Stinnerfb161b12013-04-18 01:44:27 +02007573static int
7574charmap_decode_string(const char *s,
7575 Py_ssize_t size,
7576 PyObject *mapping,
7577 const char *errors,
7578 _PyUnicodeWriter *writer)
7579{
7580 const char *starts = s;
7581 const char *e;
7582 Py_ssize_t startinpos, endinpos;
7583 PyObject *errorHandler = NULL, *exc = NULL;
7584 Py_ssize_t maplen;
7585 enum PyUnicode_Kind mapkind;
7586 void *mapdata;
7587 Py_UCS4 x;
7588 unsigned char ch;
7589
7590 if (PyUnicode_READY(mapping) == -1)
7591 return -1;
7592
7593 maplen = PyUnicode_GET_LENGTH(mapping);
7594 mapdata = PyUnicode_DATA(mapping);
7595 mapkind = PyUnicode_KIND(mapping);
7596
7597 e = s + size;
7598
7599 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7600 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7601 * is disabled in encoding aliases, latin1 is preferred because
7602 * its implementation is faster. */
7603 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7604 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7605 Py_UCS4 maxchar = writer->maxchar;
7606
7607 assert (writer->kind == PyUnicode_1BYTE_KIND);
7608 while (s < e) {
7609 ch = *s;
7610 x = mapdata_ucs1[ch];
7611 if (x > maxchar) {
7612 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7613 goto onError;
7614 maxchar = writer->maxchar;
7615 outdata = (Py_UCS1 *)writer->data;
7616 }
7617 outdata[writer->pos] = x;
7618 writer->pos++;
7619 ++s;
7620 }
7621 return 0;
7622 }
7623
7624 while (s < e) {
7625 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7626 enum PyUnicode_Kind outkind = writer->kind;
7627 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7628 if (outkind == PyUnicode_1BYTE_KIND) {
7629 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7630 Py_UCS4 maxchar = writer->maxchar;
7631 while (s < e) {
7632 ch = *s;
7633 x = mapdata_ucs2[ch];
7634 if (x > maxchar)
7635 goto Error;
7636 outdata[writer->pos] = x;
7637 writer->pos++;
7638 ++s;
7639 }
7640 break;
7641 }
7642 else if (outkind == PyUnicode_2BYTE_KIND) {
7643 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7644 while (s < e) {
7645 ch = *s;
7646 x = mapdata_ucs2[ch];
7647 if (x == 0xFFFE)
7648 goto Error;
7649 outdata[writer->pos] = x;
7650 writer->pos++;
7651 ++s;
7652 }
7653 break;
7654 }
7655 }
7656 ch = *s;
7657
7658 if (ch < maplen)
7659 x = PyUnicode_READ(mapkind, mapdata, ch);
7660 else
7661 x = 0xfffe; /* invalid value */
7662Error:
7663 if (x == 0xfffe)
7664 {
7665 /* undefined mapping */
7666 startinpos = s-starts;
7667 endinpos = startinpos+1;
7668 if (unicode_decode_call_errorhandler_writer(
7669 errors, &errorHandler,
7670 "charmap", "character maps to <undefined>",
7671 &starts, &e, &startinpos, &endinpos, &exc, &s,
7672 writer)) {
7673 goto onError;
7674 }
7675 continue;
7676 }
7677
7678 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7679 goto onError;
7680 ++s;
7681 }
7682 Py_XDECREF(errorHandler);
7683 Py_XDECREF(exc);
7684 return 0;
7685
7686onError:
7687 Py_XDECREF(errorHandler);
7688 Py_XDECREF(exc);
7689 return -1;
7690}
7691
7692static int
7693charmap_decode_mapping(const char *s,
7694 Py_ssize_t size,
7695 PyObject *mapping,
7696 const char *errors,
7697 _PyUnicodeWriter *writer)
7698{
7699 const char *starts = s;
7700 const char *e;
7701 Py_ssize_t startinpos, endinpos;
7702 PyObject *errorHandler = NULL, *exc = NULL;
7703 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007704 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007705
7706 e = s + size;
7707
7708 while (s < e) {
7709 ch = *s;
7710
7711 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7712 key = PyLong_FromLong((long)ch);
7713 if (key == NULL)
7714 goto onError;
7715
7716 item = PyObject_GetItem(mapping, key);
7717 Py_DECREF(key);
7718 if (item == NULL) {
7719 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7720 /* No mapping found means: mapping is undefined. */
7721 PyErr_Clear();
7722 goto Undefined;
7723 } else
7724 goto onError;
7725 }
7726
7727 /* Apply mapping */
7728 if (item == Py_None)
7729 goto Undefined;
7730 if (PyLong_Check(item)) {
7731 long value = PyLong_AS_LONG(item);
7732 if (value == 0xFFFE)
7733 goto Undefined;
7734 if (value < 0 || value > MAX_UNICODE) {
7735 PyErr_Format(PyExc_TypeError,
7736 "character mapping must be in range(0x%lx)",
7737 (unsigned long)MAX_UNICODE + 1);
7738 goto onError;
7739 }
7740
7741 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7742 goto onError;
7743 }
7744 else if (PyUnicode_Check(item)) {
7745 if (PyUnicode_READY(item) == -1)
7746 goto onError;
7747 if (PyUnicode_GET_LENGTH(item) == 1) {
7748 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7749 if (value == 0xFFFE)
7750 goto Undefined;
7751 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7752 goto onError;
7753 }
7754 else {
7755 writer->overallocate = 1;
7756 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7757 goto onError;
7758 }
7759 }
7760 else {
7761 /* wrong return value */
7762 PyErr_SetString(PyExc_TypeError,
7763 "character mapping must return integer, None or str");
7764 goto onError;
7765 }
7766 Py_CLEAR(item);
7767 ++s;
7768 continue;
7769
7770Undefined:
7771 /* undefined mapping */
7772 Py_CLEAR(item);
7773 startinpos = s-starts;
7774 endinpos = startinpos+1;
7775 if (unicode_decode_call_errorhandler_writer(
7776 errors, &errorHandler,
7777 "charmap", "character maps to <undefined>",
7778 &starts, &e, &startinpos, &endinpos, &exc, &s,
7779 writer)) {
7780 goto onError;
7781 }
7782 }
7783 Py_XDECREF(errorHandler);
7784 Py_XDECREF(exc);
7785 return 0;
7786
7787onError:
7788 Py_XDECREF(item);
7789 Py_XDECREF(errorHandler);
7790 Py_XDECREF(exc);
7791 return -1;
7792}
7793
Alexander Belopolsky40018472011-02-26 01:02:56 +00007794PyObject *
7795PyUnicode_DecodeCharmap(const char *s,
7796 Py_ssize_t size,
7797 PyObject *mapping,
7798 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007799{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007800 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007801
Guido van Rossumd57fd912000-03-10 22:53:23 +00007802 /* Default to Latin-1 */
7803 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007805
Guido van Rossumd57fd912000-03-10 22:53:23 +00007806 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007807 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007808 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007809 writer.min_length = size;
7810 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007811 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007812
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007813 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007814 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7815 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007816 }
7817 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007818 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7819 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007820 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007821 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007822
Benjamin Peterson29060642009-01-31 22:14:21 +00007823 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007824 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007825 return NULL;
7826}
7827
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007828/* Charmap encoding: the lookup table */
7829
Alexander Belopolsky40018472011-02-26 01:02:56 +00007830struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 PyObject_HEAD
7832 unsigned char level1[32];
7833 int count2, count3;
7834 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835};
7836
7837static PyObject*
7838encoding_map_size(PyObject *obj, PyObject* args)
7839{
7840 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007841 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007842 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843}
7844
7845static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007846 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 PyDoc_STR("Return the size (in bytes) of this object") },
7848 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007849};
7850
7851static void
7852encoding_map_dealloc(PyObject* o)
7853{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855}
7856
7857static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007858 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 "EncodingMap", /*tp_name*/
7860 sizeof(struct encoding_map), /*tp_basicsize*/
7861 0, /*tp_itemsize*/
7862 /* methods */
7863 encoding_map_dealloc, /*tp_dealloc*/
7864 0, /*tp_print*/
7865 0, /*tp_getattr*/
7866 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007867 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007868 0, /*tp_repr*/
7869 0, /*tp_as_number*/
7870 0, /*tp_as_sequence*/
7871 0, /*tp_as_mapping*/
7872 0, /*tp_hash*/
7873 0, /*tp_call*/
7874 0, /*tp_str*/
7875 0, /*tp_getattro*/
7876 0, /*tp_setattro*/
7877 0, /*tp_as_buffer*/
7878 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7879 0, /*tp_doc*/
7880 0, /*tp_traverse*/
7881 0, /*tp_clear*/
7882 0, /*tp_richcompare*/
7883 0, /*tp_weaklistoffset*/
7884 0, /*tp_iter*/
7885 0, /*tp_iternext*/
7886 encoding_map_methods, /*tp_methods*/
7887 0, /*tp_members*/
7888 0, /*tp_getset*/
7889 0, /*tp_base*/
7890 0, /*tp_dict*/
7891 0, /*tp_descr_get*/
7892 0, /*tp_descr_set*/
7893 0, /*tp_dictoffset*/
7894 0, /*tp_init*/
7895 0, /*tp_alloc*/
7896 0, /*tp_new*/
7897 0, /*tp_free*/
7898 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899};
7900
7901PyObject*
7902PyUnicode_BuildEncodingMap(PyObject* string)
7903{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 PyObject *result;
7905 struct encoding_map *mresult;
7906 int i;
7907 int need_dict = 0;
7908 unsigned char level1[32];
7909 unsigned char level2[512];
7910 unsigned char *mlevel1, *mlevel2, *mlevel3;
7911 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007912 int kind;
7913 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007914 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007915 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007917 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007918 PyErr_BadArgument();
7919 return NULL;
7920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007921 kind = PyUnicode_KIND(string);
7922 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007923 length = PyUnicode_GET_LENGTH(string);
7924 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925 memset(level1, 0xFF, sizeof level1);
7926 memset(level2, 0xFF, sizeof level2);
7927
7928 /* If there isn't a one-to-one mapping of NULL to \0,
7929 or if there are non-BMP characters, we need to use
7930 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007931 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007932 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007933 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007935 ch = PyUnicode_READ(kind, data, i);
7936 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 need_dict = 1;
7938 break;
7939 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007940 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 /* unmapped character */
7942 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007943 l1 = ch >> 11;
7944 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945 if (level1[l1] == 0xFF)
7946 level1[l1] = count2++;
7947 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007948 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949 }
7950
7951 if (count2 >= 0xFF || count3 >= 0xFF)
7952 need_dict = 1;
7953
7954 if (need_dict) {
7955 PyObject *result = PyDict_New();
7956 PyObject *key, *value;
7957 if (!result)
7958 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007959 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007960 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007961 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007962 if (!key || !value)
7963 goto failed1;
7964 if (PyDict_SetItem(result, key, value) == -1)
7965 goto failed1;
7966 Py_DECREF(key);
7967 Py_DECREF(value);
7968 }
7969 return result;
7970 failed1:
7971 Py_XDECREF(key);
7972 Py_XDECREF(value);
7973 Py_DECREF(result);
7974 return NULL;
7975 }
7976
7977 /* Create a three-level trie */
7978 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7979 16*count2 + 128*count3 - 1);
7980 if (!result)
7981 return PyErr_NoMemory();
7982 PyObject_Init(result, &EncodingMapType);
7983 mresult = (struct encoding_map*)result;
7984 mresult->count2 = count2;
7985 mresult->count3 = count3;
7986 mlevel1 = mresult->level1;
7987 mlevel2 = mresult->level23;
7988 mlevel3 = mresult->level23 + 16*count2;
7989 memcpy(mlevel1, level1, 32);
7990 memset(mlevel2, 0xFF, 16*count2);
7991 memset(mlevel3, 0, 128*count3);
7992 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007993 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007995 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7996 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007997 /* unmapped character */
7998 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007999 o1 = ch>>11;
8000 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008001 i2 = 16*mlevel1[o1] + o2;
8002 if (mlevel2[i2] == 0xFF)
8003 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008004 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 i3 = 128*mlevel2[i2] + o3;
8006 mlevel3[i3] = i;
8007 }
8008 return result;
8009}
8010
8011static int
Victor Stinner22168992011-11-20 17:09:18 +01008012encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013{
8014 struct encoding_map *map = (struct encoding_map*)mapping;
8015 int l1 = c>>11;
8016 int l2 = (c>>7) & 0xF;
8017 int l3 = c & 0x7F;
8018 int i;
8019
Victor Stinner22168992011-11-20 17:09:18 +01008020 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008022 if (c == 0)
8023 return 0;
8024 /* level 1*/
8025 i = map->level1[l1];
8026 if (i == 0xFF) {
8027 return -1;
8028 }
8029 /* level 2*/
8030 i = map->level23[16*i+l2];
8031 if (i == 0xFF) {
8032 return -1;
8033 }
8034 /* level 3 */
8035 i = map->level23[16*map->count2 + 128*i + l3];
8036 if (i == 0) {
8037 return -1;
8038 }
8039 return i;
8040}
8041
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042/* Lookup the character ch in the mapping. If the character
8043 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008044 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008045static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008046charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047{
Christian Heimes217cfd12007-12-02 14:31:20 +00008048 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049 PyObject *x;
8050
8051 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053 x = PyObject_GetItem(mapping, w);
8054 Py_DECREF(w);
8055 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8057 /* No mapping found means: mapping is undefined. */
8058 PyErr_Clear();
8059 x = Py_None;
8060 Py_INCREF(x);
8061 return x;
8062 } else
8063 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008064 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008065 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008066 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008067 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008068 long value = PyLong_AS_LONG(x);
8069 if (value < 0 || value > 255) {
8070 PyErr_SetString(PyExc_TypeError,
8071 "character mapping must be in range(256)");
8072 Py_DECREF(x);
8073 return NULL;
8074 }
8075 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008076 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008077 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 /* wrong return value */
8081 PyErr_Format(PyExc_TypeError,
8082 "character mapping must return integer, bytes or None, not %.400s",
8083 x->ob_type->tp_name);
8084 Py_DECREF(x);
8085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086 }
8087}
8088
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008090charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008092 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8093 /* exponentially overallocate to minimize reallocations */
8094 if (requiredsize < 2*outsize)
8095 requiredsize = 2*outsize;
8096 if (_PyBytes_Resize(outobj, requiredsize))
8097 return -1;
8098 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099}
8100
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008103} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008104/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008105 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 space is available. Return a new reference to the object that
8107 was put in the output buffer, or Py_None, if the mapping was undefined
8108 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008109 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008110static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008111charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008112 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114 PyObject *rep;
8115 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008116 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117
Christian Heimes90aa7642007-12-19 02:45:37 +00008118 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 if (res == -1)
8122 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 if (outsize<requiredsize)
8124 if (charmapencode_resize(outobj, outpos, requiredsize))
8125 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008126 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 outstart[(*outpos)++] = (char)res;
8128 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008129 }
8130
8131 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008133 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 Py_DECREF(rep);
8136 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008137 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 if (PyLong_Check(rep)) {
8139 Py_ssize_t requiredsize = *outpos+1;
8140 if (outsize<requiredsize)
8141 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8142 Py_DECREF(rep);
8143 return enc_EXCEPTION;
8144 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008145 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 else {
8149 const char *repchars = PyBytes_AS_STRING(rep);
8150 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8151 Py_ssize_t requiredsize = *outpos+repsize;
8152 if (outsize<requiredsize)
8153 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8154 Py_DECREF(rep);
8155 return enc_EXCEPTION;
8156 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008157 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008158 memcpy(outstart + *outpos, repchars, repsize);
8159 *outpos += repsize;
8160 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008162 Py_DECREF(rep);
8163 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164}
8165
8166/* handle an error in PyUnicode_EncodeCharmap
8167 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008168static int
8169charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008170 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008172 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008173 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008174{
8175 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008176 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008177 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008178 enum PyUnicode_Kind kind;
8179 void *data;
8180 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008181 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008182 Py_ssize_t collstartpos = *inpos;
8183 Py_ssize_t collendpos = *inpos+1;
8184 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185 char *encoding = "charmap";
8186 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008188 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008189 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190
Benjamin Petersonbac79492012-01-14 13:34:47 -05008191 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008192 return -1;
8193 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008194 /* find all unencodable characters */
8195 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008197 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008199 val = encoding_map_lookup(ch, mapping);
8200 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008201 break;
8202 ++collendpos;
8203 continue;
8204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8207 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 if (rep==NULL)
8209 return -1;
8210 else if (rep!=Py_None) {
8211 Py_DECREF(rep);
8212 break;
8213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008214 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 }
8217 /* cache callback name lookup
8218 * (if not done yet, i.e. it's the first error) */
8219 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 if ((errors==NULL) || (!strcmp(errors, "strict")))
8221 *known_errorHandler = 1;
8222 else if (!strcmp(errors, "replace"))
8223 *known_errorHandler = 2;
8224 else if (!strcmp(errors, "ignore"))
8225 *known_errorHandler = 3;
8226 else if (!strcmp(errors, "xmlcharrefreplace"))
8227 *known_errorHandler = 4;
8228 else
8229 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 }
8231 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008233 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008234 return -1;
8235 case 2: /* replace */
8236 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 x = charmapencode_output('?', mapping, res, respos);
8238 if (x==enc_EXCEPTION) {
8239 return -1;
8240 }
8241 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008242 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 return -1;
8244 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008245 }
8246 /* fall through */
8247 case 3: /* ignore */
8248 *inpos = collendpos;
8249 break;
8250 case 4: /* xmlcharrefreplace */
8251 /* generate replacement (temporarily (mis)uses p) */
8252 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 char buffer[2+29+1+1];
8254 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008255 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 for (cp = buffer; *cp; ++cp) {
8257 x = charmapencode_output(*cp, mapping, res, respos);
8258 if (x==enc_EXCEPTION)
8259 return -1;
8260 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008261 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008262 return -1;
8263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 }
8265 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008266 *inpos = collendpos;
8267 break;
8268 default:
8269 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008272 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008274 if (PyBytes_Check(repunicode)) {
8275 /* Directly copy bytes result to output. */
8276 Py_ssize_t outsize = PyBytes_Size(*res);
8277 Py_ssize_t requiredsize;
8278 repsize = PyBytes_Size(repunicode);
8279 requiredsize = *respos + repsize;
8280 if (requiredsize > outsize)
8281 /* Make room for all additional bytes. */
8282 if (charmapencode_resize(res, respos, requiredsize)) {
8283 Py_DECREF(repunicode);
8284 return -1;
8285 }
8286 memcpy(PyBytes_AsString(*res) + *respos,
8287 PyBytes_AsString(repunicode), repsize);
8288 *respos += repsize;
8289 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008290 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008291 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008293 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008294 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008295 Py_DECREF(repunicode);
8296 return -1;
8297 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008298 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008299 data = PyUnicode_DATA(repunicode);
8300 kind = PyUnicode_KIND(repunicode);
8301 for (index = 0; index < repsize; index++) {
8302 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8303 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008305 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 return -1;
8307 }
8308 else if (x==enc_FAILED) {
8309 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008310 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 return -1;
8312 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008313 }
8314 *inpos = newpos;
8315 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 }
8317 return 0;
8318}
8319
Alexander Belopolsky40018472011-02-26 01:02:56 +00008320PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008321_PyUnicode_EncodeCharmap(PyObject *unicode,
8322 PyObject *mapping,
8323 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008324{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 /* output object */
8326 PyObject *res = NULL;
8327 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008328 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008329 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008331 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 PyObject *errorHandler = NULL;
8333 PyObject *exc = NULL;
8334 /* the following variable is used for caching string comparisons
8335 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8336 * 3=ignore, 4=xmlcharrefreplace */
8337 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008338 void *data;
8339 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340
Benjamin Petersonbac79492012-01-14 13:34:47 -05008341 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008342 return NULL;
8343 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008344 data = PyUnicode_DATA(unicode);
8345 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346
Guido van Rossumd57fd912000-03-10 22:53:23 +00008347 /* Default to Latin-1 */
8348 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351 /* allocate enough for a simple encoding without
8352 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008353 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 if (res == NULL)
8355 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008356 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008360 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008362 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 if (x==enc_EXCEPTION) /* error */
8364 goto onError;
8365 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008366 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 &exc,
8368 &known_errorHandler, &errorHandler, errors,
8369 &res, &respos)) {
8370 goto onError;
8371 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008372 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 else
8374 /* done with this character => adjust input position */
8375 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008379 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008380 if (_PyBytes_Resize(&res, respos) < 0)
8381 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008382
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 Py_XDECREF(exc);
8384 Py_XDECREF(errorHandler);
8385 return res;
8386
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 Py_XDECREF(res);
8389 Py_XDECREF(exc);
8390 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 return NULL;
8392}
8393
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008394/* Deprecated */
8395PyObject *
8396PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8397 Py_ssize_t size,
8398 PyObject *mapping,
8399 const char *errors)
8400{
8401 PyObject *result;
8402 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8403 if (unicode == NULL)
8404 return NULL;
8405 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8406 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008407 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408}
8409
Alexander Belopolsky40018472011-02-26 01:02:56 +00008410PyObject *
8411PyUnicode_AsCharmapString(PyObject *unicode,
8412 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008413{
8414 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 PyErr_BadArgument();
8416 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008417 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008418 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008419}
8420
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008422static void
8423make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425 Py_ssize_t startpos, Py_ssize_t endpos,
8426 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008429 *exceptionObject = _PyUnicodeTranslateError_Create(
8430 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431 }
8432 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8434 goto onError;
8435 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8436 goto onError;
8437 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8438 goto onError;
8439 return;
8440 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008441 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442 }
8443}
8444
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445/* error handling callback helper:
8446 build arguments, call the callback and check the arguments,
8447 put the result into newpos and return the replacement string, which
8448 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008449static PyObject *
8450unicode_translate_call_errorhandler(const char *errors,
8451 PyObject **errorHandler,
8452 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008453 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008454 Py_ssize_t startpos, Py_ssize_t endpos,
8455 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008457 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008458
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008459 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 PyObject *restuple;
8461 PyObject *resunicode;
8462
8463 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 }
8468
8469 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473
8474 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008479 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 Py_DECREF(restuple);
8481 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 }
8483 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 &resunicode, &i_newpos)) {
8485 Py_DECREF(restuple);
8486 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008488 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008490 else
8491 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008493 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 Py_DECREF(restuple);
8495 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008496 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497 Py_INCREF(resunicode);
8498 Py_DECREF(restuple);
8499 return resunicode;
8500}
8501
8502/* Lookup the character ch in the mapping and put the result in result,
8503 which must be decrefed by the caller.
8504 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008506charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507{
Christian Heimes217cfd12007-12-02 14:31:20 +00008508 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 PyObject *x;
8510
8511 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513 x = PyObject_GetItem(mapping, w);
8514 Py_DECREF(w);
8515 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8517 /* No mapping found means: use 1:1 mapping. */
8518 PyErr_Clear();
8519 *result = NULL;
8520 return 0;
8521 } else
8522 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008523 }
8524 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 *result = x;
8526 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008528 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 long value = PyLong_AS_LONG(x);
8530 long max = PyUnicode_GetMax();
8531 if (value < 0 || value > max) {
8532 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008533 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 Py_DECREF(x);
8535 return -1;
8536 }
8537 *result = x;
8538 return 0;
8539 }
8540 else if (PyUnicode_Check(x)) {
8541 *result = x;
8542 return 0;
8543 }
8544 else {
8545 /* wrong return value */
8546 PyErr_SetString(PyExc_TypeError,
8547 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008548 Py_DECREF(x);
8549 return -1;
8550 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551}
8552/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 if not reallocate and adjust various state variables.
8554 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008560 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008561 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 /* exponentially overallocate to minimize reallocations */
8563 if (requiredsize < 2 * oldsize)
8564 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008565 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8566 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008568 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 }
8571 return 0;
8572}
8573/* lookup the character, put the result in the output string and adjust
8574 various state variables. Return a new reference to the object that
8575 was put in the output buffer in *result, or Py_None, if the mapping was
8576 undefined (in which case no character was written).
8577 The called must decref result.
8578 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008579static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8581 PyObject *mapping, Py_UCS4 **output,
8582 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008583 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8586 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 }
8592 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008594 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 }
8598 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 Py_ssize_t repsize;
8600 if (PyUnicode_READY(*res) == -1)
8601 return -1;
8602 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 if (repsize==1) {
8604 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 }
8607 else if (repsize!=0) {
8608 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 Py_ssize_t requiredsize = *opos +
8610 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 Py_ssize_t i;
8613 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 for(i = 0; i < repsize; i++)
8616 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 }
8619 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621 return 0;
8622}
8623
Alexander Belopolsky40018472011-02-26 01:02:56 +00008624PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625_PyUnicode_TranslateCharmap(PyObject *input,
8626 PyObject *mapping,
8627 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008628{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 /* input object */
8630 char *idata;
8631 Py_ssize_t size, i;
8632 int kind;
8633 /* output buffer */
8634 Py_UCS4 *output = NULL;
8635 Py_ssize_t osize;
8636 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 char *reason = "character maps to <undefined>";
8640 PyObject *errorHandler = NULL;
8641 PyObject *exc = NULL;
8642 /* the following variable is used for caching string comparisons
8643 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8644 * 3=ignore, 4=xmlcharrefreplace */
8645 int known_errorHandler = -1;
8646
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 PyErr_BadArgument();
8649 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 if (PyUnicode_READY(input) == -1)
8653 return NULL;
8654 idata = (char*)PyUnicode_DATA(input);
8655 kind = PyUnicode_KIND(input);
8656 size = PyUnicode_GET_LENGTH(input);
8657 i = 0;
8658
8659 if (size == 0) {
8660 Py_INCREF(input);
8661 return input;
8662 }
8663
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 /* allocate enough for a simple 1:1 translation without
8665 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 osize = size;
8667 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8668 opos = 0;
8669 if (output == NULL) {
8670 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 /* try to encode it */
8676 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 if (charmaptranslate_output(input, i, mapping,
8678 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 Py_XDECREF(x);
8680 goto onError;
8681 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008682 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 else { /* untranslatable character */
8686 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8687 Py_ssize_t repsize;
8688 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 Py_ssize_t collstart = i;
8692 Py_ssize_t collend = i+1;
8693 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 while (collend < size) {
8697 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 goto onError;
8699 Py_XDECREF(x);
8700 if (x!=Py_None)
8701 break;
8702 ++collend;
8703 }
8704 /* cache callback name lookup
8705 * (if not done yet, i.e. it's the first error) */
8706 if (known_errorHandler==-1) {
8707 if ((errors==NULL) || (!strcmp(errors, "strict")))
8708 known_errorHandler = 1;
8709 else if (!strcmp(errors, "replace"))
8710 known_errorHandler = 2;
8711 else if (!strcmp(errors, "ignore"))
8712 known_errorHandler = 3;
8713 else if (!strcmp(errors, "xmlcharrefreplace"))
8714 known_errorHandler = 4;
8715 else
8716 known_errorHandler = 0;
8717 }
8718 switch (known_errorHandler) {
8719 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008720 make_translate_exception(&exc,
8721 input, collstart, collend, reason);
8722 if (exc != NULL)
8723 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008724 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 case 2: /* replace */
8726 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 for (coll = collstart; coll<collend; coll++)
8728 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 /* fall through */
8730 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 break;
8733 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 /* generate replacement (temporarily (mis)uses i) */
8735 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 char buffer[2+29+1+1];
8737 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8739 if (charmaptranslate_makespace(&output, &osize,
8740 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 goto onError;
8742 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 break;
8747 default:
8748 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 reason, input, &exc,
8750 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008751 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008752 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008753 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008754 Py_DECREF(repunicode);
8755 goto onError;
8756 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 repsize = PyUnicode_GET_LENGTH(repunicode);
8759 if (charmaptranslate_makespace(&output, &osize,
8760 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 Py_DECREF(repunicode);
8762 goto onError;
8763 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764 for (uni2 = 0; repsize-->0; ++uni2)
8765 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8766 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008769 }
8770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8772 if (!res)
8773 goto onError;
8774 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008775 Py_XDECREF(exc);
8776 Py_XDECREF(errorHandler);
8777 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008778
Benjamin Peterson29060642009-01-31 22:14:21 +00008779 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 Py_XDECREF(exc);
8782 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008783 return NULL;
8784}
8785
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008786/* Deprecated. Use PyUnicode_Translate instead. */
8787PyObject *
8788PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8789 Py_ssize_t size,
8790 PyObject *mapping,
8791 const char *errors)
8792{
Christian Heimes5f520f42012-09-11 14:03:25 +02008793 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8795 if (!unicode)
8796 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008797 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8798 Py_DECREF(unicode);
8799 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800}
8801
Alexander Belopolsky40018472011-02-26 01:02:56 +00008802PyObject *
8803PyUnicode_Translate(PyObject *str,
8804 PyObject *mapping,
8805 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008806{
8807 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008808
Guido van Rossumd57fd912000-03-10 22:53:23 +00008809 str = PyUnicode_FromObject(str);
8810 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008811 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008812 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008813 Py_DECREF(str);
8814 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815}
Tim Petersced69f82003-09-16 20:30:58 +00008816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008818fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819{
8820 /* No need to call PyUnicode_READY(self) because this function is only
8821 called as a callback from fixup() which does it already. */
8822 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8823 const int kind = PyUnicode_KIND(self);
8824 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008825 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008826 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008827 Py_ssize_t i;
8828
8829 for (i = 0; i < len; ++i) {
8830 ch = PyUnicode_READ(kind, data, i);
8831 fixed = 0;
8832 if (ch > 127) {
8833 if (Py_UNICODE_ISSPACE(ch))
8834 fixed = ' ';
8835 else {
8836 const int decimal = Py_UNICODE_TODECIMAL(ch);
8837 if (decimal >= 0)
8838 fixed = '0' + decimal;
8839 }
8840 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008841 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008842 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008843 PyUnicode_WRITE(kind, data, i, fixed);
8844 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008845 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008846 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008847 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008848 }
8849
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008850 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851}
8852
8853PyObject *
8854_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8855{
8856 if (!PyUnicode_Check(unicode)) {
8857 PyErr_BadInternalCall();
8858 return NULL;
8859 }
8860 if (PyUnicode_READY(unicode) == -1)
8861 return NULL;
8862 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8863 /* If the string is already ASCII, just return the same string */
8864 Py_INCREF(unicode);
8865 return unicode;
8866 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008867 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868}
8869
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870PyObject *
8871PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8872 Py_ssize_t length)
8873{
Victor Stinnerf0124502011-11-21 23:12:56 +01008874 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008875 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008876 Py_UCS4 maxchar;
8877 enum PyUnicode_Kind kind;
8878 void *data;
8879
Victor Stinner99d7ad02012-02-22 13:37:39 +01008880 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008881 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008882 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008883 if (ch > 127) {
8884 int decimal = Py_UNICODE_TODECIMAL(ch);
8885 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008886 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008887 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008888 }
8889 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008890
8891 /* Copy to a new string */
8892 decimal = PyUnicode_New(length, maxchar);
8893 if (decimal == NULL)
8894 return decimal;
8895 kind = PyUnicode_KIND(decimal);
8896 data = PyUnicode_DATA(decimal);
8897 /* Iterate over code points */
8898 for (i = 0; i < length; i++) {
8899 Py_UNICODE ch = s[i];
8900 if (ch > 127) {
8901 int decimal = Py_UNICODE_TODECIMAL(ch);
8902 if (decimal >= 0)
8903 ch = '0' + decimal;
8904 }
8905 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008907 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008908}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008909/* --- Decimal Encoder ---------------------------------------------------- */
8910
Alexander Belopolsky40018472011-02-26 01:02:56 +00008911int
8912PyUnicode_EncodeDecimal(Py_UNICODE *s,
8913 Py_ssize_t length,
8914 char *output,
8915 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008916{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008917 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008918 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008919 enum PyUnicode_Kind kind;
8920 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008921
8922 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 PyErr_BadArgument();
8924 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008925 }
8926
Victor Stinner42bf7752011-11-21 22:52:58 +01008927 unicode = PyUnicode_FromUnicode(s, length);
8928 if (unicode == NULL)
8929 return -1;
8930
Benjamin Petersonbac79492012-01-14 13:34:47 -05008931 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008932 Py_DECREF(unicode);
8933 return -1;
8934 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008935 kind = PyUnicode_KIND(unicode);
8936 data = PyUnicode_DATA(unicode);
8937
Victor Stinnerb84d7232011-11-22 01:50:07 +01008938 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008939 PyObject *exc;
8940 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008942 Py_ssize_t startpos;
8943
8944 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008945
Benjamin Peterson29060642009-01-31 22:14:21 +00008946 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008947 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008948 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008950 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008951 decimal = Py_UNICODE_TODECIMAL(ch);
8952 if (decimal >= 0) {
8953 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008954 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 continue;
8956 }
8957 if (0 < ch && ch < 256) {
8958 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008959 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008960 continue;
8961 }
Victor Stinner6345be92011-11-25 20:09:01 +01008962
Victor Stinner42bf7752011-11-21 22:52:58 +01008963 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008964 exc = NULL;
8965 raise_encode_exception(&exc, "decimal", unicode,
8966 startpos, startpos+1,
8967 "invalid decimal Unicode string");
8968 Py_XDECREF(exc);
8969 Py_DECREF(unicode);
8970 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008971 }
8972 /* 0-terminate the output string */
8973 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008974 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008975 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008976}
8977
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978/* --- Helpers ------------------------------------------------------------ */
8979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008981any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 Py_ssize_t start,
8983 Py_ssize_t end)
8984{
8985 int kind1, kind2, kind;
8986 void *buf1, *buf2;
8987 Py_ssize_t len1, len2, result;
8988
8989 kind1 = PyUnicode_KIND(s1);
8990 kind2 = PyUnicode_KIND(s2);
8991 kind = kind1 > kind2 ? kind1 : kind2;
8992 buf1 = PyUnicode_DATA(s1);
8993 buf2 = PyUnicode_DATA(s2);
8994 if (kind1 != kind)
8995 buf1 = _PyUnicode_AsKind(s1, kind);
8996 if (!buf1)
8997 return -2;
8998 if (kind2 != kind)
8999 buf2 = _PyUnicode_AsKind(s2, kind);
9000 if (!buf2) {
9001 if (kind1 != kind) PyMem_Free(buf1);
9002 return -2;
9003 }
9004 len1 = PyUnicode_GET_LENGTH(s1);
9005 len2 = PyUnicode_GET_LENGTH(s2);
9006
Victor Stinner794d5672011-10-10 03:21:36 +02009007 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009008 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009009 case PyUnicode_1BYTE_KIND:
9010 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9011 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9012 else
9013 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9014 break;
9015 case PyUnicode_2BYTE_KIND:
9016 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9017 break;
9018 case PyUnicode_4BYTE_KIND:
9019 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9020 break;
9021 default:
9022 assert(0); result = -2;
9023 }
9024 }
9025 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009026 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009027 case PyUnicode_1BYTE_KIND:
9028 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9029 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9030 else
9031 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9032 break;
9033 case PyUnicode_2BYTE_KIND:
9034 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9035 break;
9036 case PyUnicode_4BYTE_KIND:
9037 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9038 break;
9039 default:
9040 assert(0); result = -2;
9041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042 }
9043
9044 if (kind1 != kind)
9045 PyMem_Free(buf1);
9046 if (kind2 != kind)
9047 PyMem_Free(buf2);
9048
9049 return result;
9050}
9051
9052Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009053_PyUnicode_InsertThousandsGrouping(
9054 PyObject *unicode, Py_ssize_t index,
9055 Py_ssize_t n_buffer,
9056 void *digits, Py_ssize_t n_digits,
9057 Py_ssize_t min_width,
9058 const char *grouping, PyObject *thousands_sep,
9059 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009060{
Victor Stinner41a863c2012-02-24 00:37:51 +01009061 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009062 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009063 Py_ssize_t thousands_sep_len;
9064 Py_ssize_t len;
9065
9066 if (unicode != NULL) {
9067 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009068 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 }
9070 else {
9071 kind = PyUnicode_1BYTE_KIND;
9072 data = NULL;
9073 }
9074 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9075 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9076 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9077 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009078 if (thousands_sep_kind < kind) {
9079 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9080 if (!thousands_sep_data)
9081 return -1;
9082 }
9083 else {
9084 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9085 if (!data)
9086 return -1;
9087 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009088 }
9089
Benjamin Petersonead6b532011-12-20 17:23:42 -06009090 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009092 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009094 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009095 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009096 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009097 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009098 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009099 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009100 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009101 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009102 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009104 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009105 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009106 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009107 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009108 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009110 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009111 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009113 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009114 break;
9115 default:
9116 assert(0);
9117 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009119 if (unicode != NULL && thousands_sep_kind != kind) {
9120 if (thousands_sep_kind < kind)
9121 PyMem_Free(thousands_sep_data);
9122 else
9123 PyMem_Free(data);
9124 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009125 if (unicode == NULL) {
9126 *maxchar = 127;
9127 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009128 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009129 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009130 }
9131 }
9132 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133}
9134
9135
Thomas Wouters477c8d52006-05-27 19:21:47 +00009136/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009137#define ADJUST_INDICES(start, end, len) \
9138 if (end > len) \
9139 end = len; \
9140 else if (end < 0) { \
9141 end += len; \
9142 if (end < 0) \
9143 end = 0; \
9144 } \
9145 if (start < 0) { \
9146 start += len; \
9147 if (start < 0) \
9148 start = 0; \
9149 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009150
Alexander Belopolsky40018472011-02-26 01:02:56 +00009151Py_ssize_t
9152PyUnicode_Count(PyObject *str,
9153 PyObject *substr,
9154 Py_ssize_t start,
9155 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009156{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009157 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009158 PyObject* str_obj;
9159 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160 int kind1, kind2, kind;
9161 void *buf1 = NULL, *buf2 = NULL;
9162 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009163
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009164 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009165 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009166 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009167 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009168 if (!sub_obj) {
9169 Py_DECREF(str_obj);
9170 return -1;
9171 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009172 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009173 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009174 Py_DECREF(str_obj);
9175 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009176 }
Tim Petersced69f82003-09-16 20:30:58 +00009177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009178 kind1 = PyUnicode_KIND(str_obj);
9179 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009180 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009183 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009184 if (kind2 > kind) {
9185 Py_DECREF(sub_obj);
9186 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009187 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009188 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009189 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009190 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 if (!buf2)
9192 goto onError;
9193 len1 = PyUnicode_GET_LENGTH(str_obj);
9194 len2 = PyUnicode_GET_LENGTH(sub_obj);
9195
9196 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009197 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009199 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9200 result = asciilib_count(
9201 ((Py_UCS1*)buf1) + start, end - start,
9202 buf2, len2, PY_SSIZE_T_MAX
9203 );
9204 else
9205 result = ucs1lib_count(
9206 ((Py_UCS1*)buf1) + start, end - start,
9207 buf2, len2, PY_SSIZE_T_MAX
9208 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 break;
9210 case PyUnicode_2BYTE_KIND:
9211 result = ucs2lib_count(
9212 ((Py_UCS2*)buf1) + start, end - start,
9213 buf2, len2, PY_SSIZE_T_MAX
9214 );
9215 break;
9216 case PyUnicode_4BYTE_KIND:
9217 result = ucs4lib_count(
9218 ((Py_UCS4*)buf1) + start, end - start,
9219 buf2, len2, PY_SSIZE_T_MAX
9220 );
9221 break;
9222 default:
9223 assert(0); result = 0;
9224 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009225
9226 Py_DECREF(sub_obj);
9227 Py_DECREF(str_obj);
9228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229 if (kind2 != kind)
9230 PyMem_Free(buf2);
9231
Guido van Rossumd57fd912000-03-10 22:53:23 +00009232 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233 onError:
9234 Py_DECREF(sub_obj);
9235 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 if (kind2 != kind && buf2)
9237 PyMem_Free(buf2);
9238 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009239}
9240
Alexander Belopolsky40018472011-02-26 01:02:56 +00009241Py_ssize_t
9242PyUnicode_Find(PyObject *str,
9243 PyObject *sub,
9244 Py_ssize_t start,
9245 Py_ssize_t end,
9246 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009248 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009249
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009251 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009252 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009253 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009254 if (!sub) {
9255 Py_DECREF(str);
9256 return -2;
9257 }
9258 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9259 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009260 Py_DECREF(str);
9261 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262 }
Tim Petersced69f82003-09-16 20:30:58 +00009263
Victor Stinner794d5672011-10-10 03:21:36 +02009264 result = any_find_slice(direction,
9265 str, sub, start, end
9266 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009267
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009269 Py_DECREF(sub);
9270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 return result;
9272}
9273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274Py_ssize_t
9275PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9276 Py_ssize_t start, Py_ssize_t end,
9277 int direction)
9278{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009280 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 if (PyUnicode_READY(str) == -1)
9282 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009283 if (start < 0 || end < 0) {
9284 PyErr_SetString(PyExc_IndexError, "string index out of range");
9285 return -2;
9286 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 if (end > PyUnicode_GET_LENGTH(str))
9288 end = PyUnicode_GET_LENGTH(str);
9289 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009290 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9291 kind, end-start, ch, direction);
9292 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009294 else
9295 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296}
9297
Alexander Belopolsky40018472011-02-26 01:02:56 +00009298static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009299tailmatch(PyObject *self,
9300 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009301 Py_ssize_t start,
9302 Py_ssize_t end,
9303 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305 int kind_self;
9306 int kind_sub;
9307 void *data_self;
9308 void *data_sub;
9309 Py_ssize_t offset;
9310 Py_ssize_t i;
9311 Py_ssize_t end_sub;
9312
9313 if (PyUnicode_READY(self) == -1 ||
9314 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316
9317 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009318 return 1;
9319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9321 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009323 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325 kind_self = PyUnicode_KIND(self);
9326 data_self = PyUnicode_DATA(self);
9327 kind_sub = PyUnicode_KIND(substring);
9328 data_sub = PyUnicode_DATA(substring);
9329 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9330
9331 if (direction > 0)
9332 offset = end;
9333 else
9334 offset = start;
9335
9336 if (PyUnicode_READ(kind_self, data_self, offset) ==
9337 PyUnicode_READ(kind_sub, data_sub, 0) &&
9338 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9339 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9340 /* If both are of the same kind, memcmp is sufficient */
9341 if (kind_self == kind_sub) {
9342 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009343 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 data_sub,
9345 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009346 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 }
9348 /* otherwise we have to compare each character by first accesing it */
9349 else {
9350 /* We do not need to compare 0 and len(substring)-1 because
9351 the if statement above ensured already that they are equal
9352 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 for (i = 1; i < end_sub; ++i) {
9354 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9355 PyUnicode_READ(kind_sub, data_sub, i))
9356 return 0;
9357 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009360 }
9361
9362 return 0;
9363}
9364
Alexander Belopolsky40018472011-02-26 01:02:56 +00009365Py_ssize_t
9366PyUnicode_Tailmatch(PyObject *str,
9367 PyObject *substr,
9368 Py_ssize_t start,
9369 Py_ssize_t end,
9370 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009372 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 str = PyUnicode_FromObject(str);
9375 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009376 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 substr = PyUnicode_FromObject(substr);
9378 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 Py_DECREF(str);
9380 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381 }
Tim Petersced69f82003-09-16 20:30:58 +00009382
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009383 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009384 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385 Py_DECREF(str);
9386 Py_DECREF(substr);
9387 return result;
9388}
9389
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390/* Apply fixfct filter to the Unicode object self and return a
9391 reference to the modified object */
9392
Alexander Belopolsky40018472011-02-26 01:02:56 +00009393static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009394fixup(PyObject *self,
9395 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397 PyObject *u;
9398 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009399 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009401 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009403 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009404 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406 /* fix functions return the new maximum character in a string,
9407 if the kind of the resulting unicode object does not change,
9408 everything is fine. Otherwise we need to change the string kind
9409 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009410 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009411
9412 if (maxchar_new == 0) {
9413 /* no changes */;
9414 if (PyUnicode_CheckExact(self)) {
9415 Py_DECREF(u);
9416 Py_INCREF(self);
9417 return self;
9418 }
9419 else
9420 return u;
9421 }
9422
Victor Stinnere6abb482012-05-02 01:15:40 +02009423 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424
Victor Stinnereaab6042011-12-11 22:22:39 +01009425 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009427
9428 /* In case the maximum character changed, we need to
9429 convert the string to the new category. */
9430 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9431 if (v == NULL) {
9432 Py_DECREF(u);
9433 return NULL;
9434 }
9435 if (maxchar_new > maxchar_old) {
9436 /* If the maxchar increased so that the kind changed, not all
9437 characters are representable anymore and we need to fix the
9438 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009439 _PyUnicode_FastCopyCharacters(v, 0,
9440 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009441 maxchar_old = fixfct(v);
9442 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 }
9444 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009445 _PyUnicode_FastCopyCharacters(v, 0,
9446 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009448 Py_DECREF(u);
9449 assert(_PyUnicode_CheckConsistency(v, 1));
9450 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451}
9452
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009453static PyObject *
9454ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009456 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9457 char *resdata, *data = PyUnicode_DATA(self);
9458 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009459
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009460 res = PyUnicode_New(len, 127);
9461 if (res == NULL)
9462 return NULL;
9463 resdata = PyUnicode_DATA(res);
9464 if (lower)
9465 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009467 _Py_bytes_upper(resdata, data, len);
9468 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469}
9470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009472handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009474 Py_ssize_t j;
9475 int final_sigma;
9476 Py_UCS4 c;
9477 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009478
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009479 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9480
9481 where ! is a negation and \p{xxx} is a character with property xxx.
9482 */
9483 for (j = i - 1; j >= 0; j--) {
9484 c = PyUnicode_READ(kind, data, j);
9485 if (!_PyUnicode_IsCaseIgnorable(c))
9486 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009488 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9489 if (final_sigma) {
9490 for (j = i + 1; j < length; j++) {
9491 c = PyUnicode_READ(kind, data, j);
9492 if (!_PyUnicode_IsCaseIgnorable(c))
9493 break;
9494 }
9495 final_sigma = j == length || !_PyUnicode_IsCased(c);
9496 }
9497 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498}
9499
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500static int
9501lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9502 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009504 /* Obscure special case. */
9505 if (c == 0x3A3) {
9506 mapped[0] = handle_capital_sigma(kind, data, length, i);
9507 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009509 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510}
9511
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009512static Py_ssize_t
9513do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009515 Py_ssize_t i, k = 0;
9516 int n_res, j;
9517 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009518
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009519 c = PyUnicode_READ(kind, data, 0);
9520 n_res = _PyUnicode_ToUpperFull(c, mapped);
9521 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009522 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009523 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525 for (i = 1; i < length; i++) {
9526 c = PyUnicode_READ(kind, data, i);
9527 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9528 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009529 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009530 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009531 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009532 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009533 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534}
9535
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536static Py_ssize_t
9537do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9538 Py_ssize_t i, k = 0;
9539
9540 for (i = 0; i < length; i++) {
9541 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9542 int n_res, j;
9543 if (Py_UNICODE_ISUPPER(c)) {
9544 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9545 }
9546 else if (Py_UNICODE_ISLOWER(c)) {
9547 n_res = _PyUnicode_ToUpperFull(c, mapped);
9548 }
9549 else {
9550 n_res = 1;
9551 mapped[0] = c;
9552 }
9553 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009554 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009555 res[k++] = mapped[j];
9556 }
9557 }
9558 return k;
9559}
9560
9561static Py_ssize_t
9562do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9563 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 Py_ssize_t i, k = 0;
9566
9567 for (i = 0; i < length; i++) {
9568 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9569 int n_res, j;
9570 if (lower)
9571 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9572 else
9573 n_res = _PyUnicode_ToUpperFull(c, mapped);
9574 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009575 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576 res[k++] = mapped[j];
9577 }
9578 }
9579 return k;
9580}
9581
9582static Py_ssize_t
9583do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9584{
9585 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9586}
9587
9588static Py_ssize_t
9589do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9590{
9591 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9592}
9593
Benjamin Petersone51757f2012-01-12 21:10:29 -05009594static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009595do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9596{
9597 Py_ssize_t i, k = 0;
9598
9599 for (i = 0; i < length; i++) {
9600 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9601 Py_UCS4 mapped[3];
9602 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9603 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009604 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009605 res[k++] = mapped[j];
9606 }
9607 }
9608 return k;
9609}
9610
9611static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009612do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9613{
9614 Py_ssize_t i, k = 0;
9615 int previous_is_cased;
9616
9617 previous_is_cased = 0;
9618 for (i = 0; i < length; i++) {
9619 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9620 Py_UCS4 mapped[3];
9621 int n_res, j;
9622
9623 if (previous_is_cased)
9624 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9625 else
9626 n_res = _PyUnicode_ToTitleFull(c, mapped);
9627
9628 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009629 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009630 res[k++] = mapped[j];
9631 }
9632
9633 previous_is_cased = _PyUnicode_IsCased(c);
9634 }
9635 return k;
9636}
9637
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638static PyObject *
9639case_operation(PyObject *self,
9640 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9641{
9642 PyObject *res = NULL;
9643 Py_ssize_t length, newlength = 0;
9644 int kind, outkind;
9645 void *data, *outdata;
9646 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9647
Benjamin Petersoneea48462012-01-16 14:28:50 -05009648 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649
9650 kind = PyUnicode_KIND(self);
9651 data = PyUnicode_DATA(self);
9652 length = PyUnicode_GET_LENGTH(self);
Antoine Pitroub6dc9b72014-10-15 23:14:53 +02009653 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009654 PyErr_SetString(PyExc_OverflowError, "string is too long");
9655 return NULL;
9656 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009657 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 if (tmp == NULL)
9659 return PyErr_NoMemory();
9660 newlength = perform(kind, data, length, tmp, &maxchar);
9661 res = PyUnicode_New(newlength, maxchar);
9662 if (res == NULL)
9663 goto leave;
9664 tmpend = tmp + newlength;
9665 outdata = PyUnicode_DATA(res);
9666 outkind = PyUnicode_KIND(res);
9667 switch (outkind) {
9668 case PyUnicode_1BYTE_KIND:
9669 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9670 break;
9671 case PyUnicode_2BYTE_KIND:
9672 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9673 break;
9674 case PyUnicode_4BYTE_KIND:
9675 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9676 break;
9677 default:
9678 assert(0);
9679 break;
9680 }
9681 leave:
9682 PyMem_FREE(tmp);
9683 return res;
9684}
9685
Tim Peters8ce9f162004-08-27 01:49:32 +00009686PyObject *
9687PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009688{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9694 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009695 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009696 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009697 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009698 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009699 int use_memcpy;
9700 unsigned char *res_data = NULL, *sep_data = NULL;
9701 PyObject *last_obj;
9702 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009703
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009704 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009705 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009706 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009707 }
9708
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009709 /* NOTE: the following code can't call back into Python code,
9710 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009711 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009712
Tim Peters05eba1f2004-08-27 21:32:02 +00009713 seqlen = PySequence_Fast_GET_SIZE(fseq);
9714 /* If empty sequence, return u"". */
9715 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009716 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009717 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009718 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009719
Tim Peters05eba1f2004-08-27 21:32:02 +00009720 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009721 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009722 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009723 if (seqlen == 1) {
9724 if (PyUnicode_CheckExact(items[0])) {
9725 res = items[0];
9726 Py_INCREF(res);
9727 Py_DECREF(fseq);
9728 return res;
9729 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009730 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009731 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009732 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009733 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009734 /* Set up sep and seplen */
9735 if (separator == NULL) {
9736 /* fall back to a blank space separator */
9737 sep = PyUnicode_FromOrdinal(' ');
9738 if (!sep)
9739 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009741 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009742 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009743 else {
9744 if (!PyUnicode_Check(separator)) {
9745 PyErr_Format(PyExc_TypeError,
9746 "separator: expected str instance,"
9747 " %.80s found",
9748 Py_TYPE(separator)->tp_name);
9749 goto onError;
9750 }
9751 if (PyUnicode_READY(separator))
9752 goto onError;
9753 sep = separator;
9754 seplen = PyUnicode_GET_LENGTH(separator);
9755 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9756 /* inc refcount to keep this code path symmetric with the
9757 above case of a blank separator */
9758 Py_INCREF(sep);
9759 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009760 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009761 }
9762
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 /* There are at least two things to join, or else we have a subclass
9764 * of str in the sequence.
9765 * Do a pre-pass to figure out the total amount of space we'll
9766 * need (sz), and see whether all argument are strings.
9767 */
9768 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009769#ifdef Py_DEBUG
9770 use_memcpy = 0;
9771#else
9772 use_memcpy = 1;
9773#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009774 for (i = 0; i < seqlen; i++) {
9775 const Py_ssize_t old_sz = sz;
9776 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009777 if (!PyUnicode_Check(item)) {
9778 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009779 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009780 " %.80s found",
9781 i, Py_TYPE(item)->tp_name);
9782 goto onError;
9783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009784 if (PyUnicode_READY(item) == -1)
9785 goto onError;
9786 sz += PyUnicode_GET_LENGTH(item);
9787 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009788 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009789 if (i != 0)
9790 sz += seplen;
9791 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9792 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009793 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 goto onError;
9795 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009796 if (use_memcpy && last_obj != NULL) {
9797 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9798 use_memcpy = 0;
9799 }
9800 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009801 }
Tim Petersced69f82003-09-16 20:30:58 +00009802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 if (res == NULL)
9805 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009806
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009807 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009808#ifdef Py_DEBUG
9809 use_memcpy = 0;
9810#else
9811 if (use_memcpy) {
9812 res_data = PyUnicode_1BYTE_DATA(res);
9813 kind = PyUnicode_KIND(res);
9814 if (seplen != 0)
9815 sep_data = PyUnicode_1BYTE_DATA(sep);
9816 }
9817#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009818 if (use_memcpy) {
9819 for (i = 0; i < seqlen; ++i) {
9820 Py_ssize_t itemlen;
9821 item = items[i];
9822
9823 /* Copy item, and maybe the separator. */
9824 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009825 Py_MEMCPY(res_data,
9826 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009827 kind * seplen);
9828 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009829 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009830
9831 itemlen = PyUnicode_GET_LENGTH(item);
9832 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009833 Py_MEMCPY(res_data,
9834 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009835 kind * itemlen);
9836 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009837 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009838 }
9839 assert(res_data == PyUnicode_1BYTE_DATA(res)
9840 + kind * PyUnicode_GET_LENGTH(res));
9841 }
9842 else {
9843 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9844 Py_ssize_t itemlen;
9845 item = items[i];
9846
9847 /* Copy item, and maybe the separator. */
9848 if (i && seplen != 0) {
9849 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9850 res_offset += seplen;
9851 }
9852
9853 itemlen = PyUnicode_GET_LENGTH(item);
9854 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009855 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009856 res_offset += itemlen;
9857 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009858 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009859 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009860 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009861
Tim Peters05eba1f2004-08-27 21:32:02 +00009862 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009864 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866
Benjamin Peterson29060642009-01-31 22:14:21 +00009867 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009868 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009870 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009871 return NULL;
9872}
9873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874#define FILL(kind, data, value, start, length) \
9875 do { \
9876 Py_ssize_t i_ = 0; \
9877 assert(kind != PyUnicode_WCHAR_KIND); \
9878 switch ((kind)) { \
9879 case PyUnicode_1BYTE_KIND: { \
9880 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009881 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 break; \
9883 } \
9884 case PyUnicode_2BYTE_KIND: { \
9885 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9886 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9887 break; \
9888 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009889 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009890 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9891 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9892 break; \
9893 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009894 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 } \
9896 } while (0)
9897
Victor Stinnerd3f08822012-05-29 12:57:52 +02009898void
9899_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9900 Py_UCS4 fill_char)
9901{
9902 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9903 const void *data = PyUnicode_DATA(unicode);
9904 assert(PyUnicode_IS_READY(unicode));
9905 assert(unicode_modifiable(unicode));
9906 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9907 assert(start >= 0);
9908 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9909 FILL(kind, data, fill_char, start, length);
9910}
9911
Victor Stinner3fe55312012-01-04 00:33:50 +01009912Py_ssize_t
9913PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9914 Py_UCS4 fill_char)
9915{
9916 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009917
9918 if (!PyUnicode_Check(unicode)) {
9919 PyErr_BadInternalCall();
9920 return -1;
9921 }
9922 if (PyUnicode_READY(unicode) == -1)
9923 return -1;
9924 if (unicode_check_modifiable(unicode))
9925 return -1;
9926
Victor Stinnerd3f08822012-05-29 12:57:52 +02009927 if (start < 0) {
9928 PyErr_SetString(PyExc_IndexError, "string index out of range");
9929 return -1;
9930 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009931 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9932 PyErr_SetString(PyExc_ValueError,
9933 "fill character is bigger than "
9934 "the string maximum character");
9935 return -1;
9936 }
9937
9938 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9939 length = Py_MIN(maxlen, length);
9940 if (length <= 0)
9941 return 0;
9942
Victor Stinnerd3f08822012-05-29 12:57:52 +02009943 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009944 return length;
9945}
9946
Victor Stinner9310abb2011-10-05 00:59:23 +02009947static PyObject *
9948pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009949 Py_ssize_t left,
9950 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 PyObject *u;
9954 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009955 int kind;
9956 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957
9958 if (left < 0)
9959 left = 0;
9960 if (right < 0)
9961 right = 0;
9962
Victor Stinnerc4b49542011-12-11 22:44:26 +01009963 if (left == 0 && right == 0)
9964 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9967 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009968 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9969 return NULL;
9970 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009972 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009974 if (!u)
9975 return NULL;
9976
9977 kind = PyUnicode_KIND(u);
9978 data = PyUnicode_DATA(u);
9979 if (left)
9980 FILL(kind, data, fill, 0, left);
9981 if (right)
9982 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009983 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009984 assert(_PyUnicode_CheckConsistency(u, 1));
9985 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986}
9987
Alexander Belopolsky40018472011-02-26 01:02:56 +00009988PyObject *
9989PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009991 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992
9993 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009994 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009995 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009996 if (PyUnicode_READY(string) == -1) {
9997 Py_DECREF(string);
9998 return NULL;
9999 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010000
Benjamin Petersonead6b532011-12-20 17:23:42 -060010001 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010003 if (PyUnicode_IS_ASCII(string))
10004 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010006 PyUnicode_GET_LENGTH(string), keepends);
10007 else
10008 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010010 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 break;
10012 case PyUnicode_2BYTE_KIND:
10013 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010014 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 PyUnicode_GET_LENGTH(string), keepends);
10016 break;
10017 case PyUnicode_4BYTE_KIND:
10018 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 PyUnicode_GET_LENGTH(string), keepends);
10021 break;
10022 default:
10023 assert(0);
10024 list = 0;
10025 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010026 Py_DECREF(string);
10027 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010028}
10029
Alexander Belopolsky40018472011-02-26 01:02:56 +000010030static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010031split(PyObject *self,
10032 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010033 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 int kind1, kind2, kind;
10036 void *buf1, *buf2;
10037 Py_ssize_t len1, len2;
10038 PyObject* out;
10039
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010041 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 if (PyUnicode_READY(self) == -1)
10044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010047 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010049 if (PyUnicode_IS_ASCII(self))
10050 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010051 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010052 PyUnicode_GET_LENGTH(self), maxcount
10053 );
10054 else
10055 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010056 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010057 PyUnicode_GET_LENGTH(self), maxcount
10058 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 case PyUnicode_2BYTE_KIND:
10060 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010061 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 PyUnicode_GET_LENGTH(self), maxcount
10063 );
10064 case PyUnicode_4BYTE_KIND:
10065 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010066 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 PyUnicode_GET_LENGTH(self), maxcount
10068 );
10069 default:
10070 assert(0);
10071 return NULL;
10072 }
10073
10074 if (PyUnicode_READY(substring) == -1)
10075 return NULL;
10076
10077 kind1 = PyUnicode_KIND(self);
10078 kind2 = PyUnicode_KIND(substring);
10079 kind = kind1 > kind2 ? kind1 : kind2;
10080 buf1 = PyUnicode_DATA(self);
10081 buf2 = PyUnicode_DATA(substring);
10082 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010083 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (!buf1)
10085 return NULL;
10086 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010087 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 if (!buf2) {
10089 if (kind1 != kind) PyMem_Free(buf1);
10090 return NULL;
10091 }
10092 len1 = PyUnicode_GET_LENGTH(self);
10093 len2 = PyUnicode_GET_LENGTH(substring);
10094
Benjamin Petersonead6b532011-12-20 17:23:42 -060010095 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010097 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10098 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010099 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 else
10101 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010102 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 break;
10104 case PyUnicode_2BYTE_KIND:
10105 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 break;
10108 case PyUnicode_4BYTE_KIND:
10109 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010110 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 break;
10112 default:
10113 out = NULL;
10114 }
10115 if (kind1 != kind)
10116 PyMem_Free(buf1);
10117 if (kind2 != kind)
10118 PyMem_Free(buf2);
10119 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010120}
10121
Alexander Belopolsky40018472011-02-26 01:02:56 +000010122static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010123rsplit(PyObject *self,
10124 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010126{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 int kind1, kind2, kind;
10128 void *buf1, *buf2;
10129 Py_ssize_t len1, len2;
10130 PyObject* out;
10131
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010132 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010133 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 if (PyUnicode_READY(self) == -1)
10136 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010139 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010141 if (PyUnicode_IS_ASCII(self))
10142 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010143 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 PyUnicode_GET_LENGTH(self), maxcount
10145 );
10146 else
10147 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010148 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 PyUnicode_GET_LENGTH(self), maxcount
10150 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 case PyUnicode_2BYTE_KIND:
10152 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 PyUnicode_GET_LENGTH(self), maxcount
10155 );
10156 case PyUnicode_4BYTE_KIND:
10157 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 PyUnicode_GET_LENGTH(self), maxcount
10160 );
10161 default:
10162 assert(0);
10163 return NULL;
10164 }
10165
10166 if (PyUnicode_READY(substring) == -1)
10167 return NULL;
10168
10169 kind1 = PyUnicode_KIND(self);
10170 kind2 = PyUnicode_KIND(substring);
10171 kind = kind1 > kind2 ? kind1 : kind2;
10172 buf1 = PyUnicode_DATA(self);
10173 buf2 = PyUnicode_DATA(substring);
10174 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010175 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (!buf1)
10177 return NULL;
10178 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010179 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (!buf2) {
10181 if (kind1 != kind) PyMem_Free(buf1);
10182 return NULL;
10183 }
10184 len1 = PyUnicode_GET_LENGTH(self);
10185 len2 = PyUnicode_GET_LENGTH(substring);
10186
Benjamin Petersonead6b532011-12-20 17:23:42 -060010187 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10190 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 else
10193 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010194 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 break;
10196 case PyUnicode_2BYTE_KIND:
10197 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 break;
10200 case PyUnicode_4BYTE_KIND:
10201 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 break;
10204 default:
10205 out = NULL;
10206 }
10207 if (kind1 != kind)
10208 PyMem_Free(buf1);
10209 if (kind2 != kind)
10210 PyMem_Free(buf2);
10211 return out;
10212}
10213
10214static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010215anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10216 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010218 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010220 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10221 return asciilib_find(buf1, len1, buf2, len2, offset);
10222 else
10223 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 case PyUnicode_2BYTE_KIND:
10225 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10226 case PyUnicode_4BYTE_KIND:
10227 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10228 }
10229 assert(0);
10230 return -1;
10231}
10232
10233static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010234anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10235 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010237 switch (kind) {
10238 case PyUnicode_1BYTE_KIND:
10239 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10240 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10241 else
10242 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10243 case PyUnicode_2BYTE_KIND:
10244 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10245 case PyUnicode_4BYTE_KIND:
10246 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10247 }
10248 assert(0);
10249 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010250}
10251
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010252static void
10253replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10254 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10255{
10256 int kind = PyUnicode_KIND(u);
10257 void *data = PyUnicode_DATA(u);
10258 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10259 if (kind == PyUnicode_1BYTE_KIND) {
10260 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10261 (Py_UCS1 *)data + len,
10262 u1, u2, maxcount);
10263 }
10264 else if (kind == PyUnicode_2BYTE_KIND) {
10265 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10266 (Py_UCS2 *)data + len,
10267 u1, u2, maxcount);
10268 }
10269 else {
10270 assert(kind == PyUnicode_4BYTE_KIND);
10271 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10272 (Py_UCS4 *)data + len,
10273 u1, u2, maxcount);
10274 }
10275}
10276
Alexander Belopolsky40018472011-02-26 01:02:56 +000010277static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278replace(PyObject *self, PyObject *str1,
10279 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 PyObject *u;
10282 char *sbuf = PyUnicode_DATA(self);
10283 char *buf1 = PyUnicode_DATA(str1);
10284 char *buf2 = PyUnicode_DATA(str2);
10285 int srelease = 0, release1 = 0, release2 = 0;
10286 int skind = PyUnicode_KIND(self);
10287 int kind1 = PyUnicode_KIND(str1);
10288 int kind2 = PyUnicode_KIND(str2);
10289 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10290 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10291 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010292 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010293 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294
10295 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010296 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010298 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299
Victor Stinner59de0ee2011-10-07 10:01:28 +020010300 if (str1 == str2)
10301 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302
Victor Stinner49a0a212011-10-12 23:46:10 +020010303 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010304 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10305 if (maxchar < maxchar_str1)
10306 /* substring too wide to be present */
10307 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010308 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10309 /* Replacing str1 with str2 may cause a maxchar reduction in the
10310 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010311 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010312 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010315 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010317 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010320 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010321 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010322
Victor Stinner69ed0f42013-04-09 21:48:24 +020010323 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010324 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010325 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010326 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010327 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010331
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010332 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10333 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 }
10335 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 int rkind = skind;
10337 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010338 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 if (kind1 < rkind) {
10341 /* widen substring */
10342 buf1 = _PyUnicode_AsKind(str1, rkind);
10343 if (!buf1) goto error;
10344 release1 = 1;
10345 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010346 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010347 if (i < 0)
10348 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 if (rkind > kind2) {
10350 /* widen replacement */
10351 buf2 = _PyUnicode_AsKind(str2, rkind);
10352 if (!buf2) goto error;
10353 release2 = 1;
10354 }
10355 else if (rkind < kind2) {
10356 /* widen self and buf1 */
10357 rkind = kind2;
10358 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010359 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 sbuf = _PyUnicode_AsKind(self, rkind);
10361 if (!sbuf) goto error;
10362 srelease = 1;
10363 buf1 = _PyUnicode_AsKind(str1, rkind);
10364 if (!buf1) goto error;
10365 release1 = 1;
10366 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010367 u = PyUnicode_New(slen, maxchar);
10368 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010370 assert(PyUnicode_KIND(u) == rkind);
10371 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010372
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010373 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010374 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010375 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010377 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010379
10380 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010381 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010382 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010383 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010384 if (i == -1)
10385 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010386 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010388 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010392 }
10393 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010395 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 int rkind = skind;
10397 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010400 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 buf1 = _PyUnicode_AsKind(str1, rkind);
10402 if (!buf1) goto error;
10403 release1 = 1;
10404 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010405 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 if (n == 0)
10407 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010409 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 buf2 = _PyUnicode_AsKind(str2, rkind);
10411 if (!buf2) goto error;
10412 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010416 rkind = kind2;
10417 sbuf = _PyUnicode_AsKind(self, rkind);
10418 if (!sbuf) goto error;
10419 srelease = 1;
10420 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010421 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 buf1 = _PyUnicode_AsKind(str1, rkind);
10423 if (!buf1) goto error;
10424 release1 = 1;
10425 }
10426 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10427 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010428 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 PyErr_SetString(PyExc_OverflowError,
10430 "replace string is too long");
10431 goto error;
10432 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010433 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010434 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010435 _Py_INCREF_UNICODE_EMPTY();
10436 if (!unicode_empty)
10437 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 u = unicode_empty;
10439 goto done;
10440 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010441 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 PyErr_SetString(PyExc_OverflowError,
10443 "replace string is too long");
10444 goto error;
10445 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010446 u = PyUnicode_New(new_size, maxchar);
10447 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010449 assert(PyUnicode_KIND(u) == rkind);
10450 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 ires = i = 0;
10452 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 while (n-- > 0) {
10454 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010455 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010457 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010458 if (j == -1)
10459 break;
10460 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010461 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010462 memcpy(res + rkind * ires,
10463 sbuf + rkind * i,
10464 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010466 }
10467 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010469 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010471 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010472 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010473 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010475 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010477 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010478 memcpy(res + rkind * ires,
10479 sbuf + rkind * i,
10480 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 }
10482 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010483 /* interleave */
10484 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010485 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010487 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 if (--n <= 0)
10490 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010491 memcpy(res + rkind * ires,
10492 sbuf + rkind * i,
10493 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 ires++;
10495 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010497 memcpy(res + rkind * ires,
10498 sbuf + rkind * i,
10499 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010501 }
10502
10503 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010504 unicode_adjust_maxchar(&u);
10505 if (u == NULL)
10506 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010508
10509 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 if (srelease)
10511 PyMem_FREE(sbuf);
10512 if (release1)
10513 PyMem_FREE(buf1);
10514 if (release2)
10515 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010516 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010518
Benjamin Peterson29060642009-01-31 22:14:21 +000010519 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010520 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (srelease)
10522 PyMem_FREE(sbuf);
10523 if (release1)
10524 PyMem_FREE(buf1);
10525 if (release2)
10526 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010527 return unicode_result_unchanged(self);
10528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 error:
10530 if (srelease && sbuf)
10531 PyMem_FREE(sbuf);
10532 if (release1 && buf1)
10533 PyMem_FREE(buf1);
10534 if (release2 && buf2)
10535 PyMem_FREE(buf2);
10536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537}
10538
10539/* --- Unicode Object Methods --------------------------------------------- */
10540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010541PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543\n\
10544Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010545characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546
10547static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010548unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010550 if (PyUnicode_READY(self) == -1)
10551 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010552 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010553}
10554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010555PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010556 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010557\n\
10558Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010559have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560
10561static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010562unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010564 if (PyUnicode_READY(self) == -1)
10565 return NULL;
10566 if (PyUnicode_GET_LENGTH(self) == 0)
10567 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010568 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569}
10570
Benjamin Petersond5890c82012-01-14 13:23:30 -050010571PyDoc_STRVAR(casefold__doc__,
10572 "S.casefold() -> str\n\
10573\n\
10574Return a version of S suitable for caseless comparisons.");
10575
10576static PyObject *
10577unicode_casefold(PyObject *self)
10578{
10579 if (PyUnicode_READY(self) == -1)
10580 return NULL;
10581 if (PyUnicode_IS_ASCII(self))
10582 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010583 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010584}
10585
10586
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010587/* Argument converter. Coerces to a single unicode character */
10588
10589static int
10590convert_uc(PyObject *obj, void *addr)
10591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010593 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010594
Benjamin Peterson14339b62009-01-31 16:36:08 +000010595 uniobj = PyUnicode_FromObject(obj);
10596 if (uniobj == NULL) {
10597 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010598 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010599 return 0;
10600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010602 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010603 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010604 Py_DECREF(uniobj);
10605 return 0;
10606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010608 Py_DECREF(uniobj);
10609 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010610}
10611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010612PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010613 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010614\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010615Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010616done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617
10618static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010619unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010621 Py_ssize_t marg, left;
10622 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 Py_UCS4 fillchar = ' ';
10624
Victor Stinnere9a29352011-10-01 02:14:59 +020010625 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010627
Benjamin Petersonbac79492012-01-14 13:34:47 -050010628 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629 return NULL;
10630
Victor Stinnerc4b49542011-12-11 22:44:26 +010010631 if (PyUnicode_GET_LENGTH(self) >= width)
10632 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010633
Victor Stinnerc4b49542011-12-11 22:44:26 +010010634 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635 left = marg / 2 + (marg & width & 1);
10636
Victor Stinner9310abb2011-10-05 00:59:23 +020010637 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638}
10639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640/* This function assumes that str1 and str2 are readied by the caller. */
10641
Marc-André Lemburge5034372000-08-08 08:04:29 +000010642static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010643unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010644{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010645#define COMPARE(TYPE1, TYPE2) \
10646 do { \
10647 TYPE1* p1 = (TYPE1 *)data1; \
10648 TYPE2* p2 = (TYPE2 *)data2; \
10649 TYPE1* end = p1 + len; \
10650 Py_UCS4 c1, c2; \
10651 for (; p1 != end; p1++, p2++) { \
10652 c1 = *p1; \
10653 c2 = *p2; \
10654 if (c1 != c2) \
10655 return (c1 < c2) ? -1 : 1; \
10656 } \
10657 } \
10658 while (0)
10659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010660 int kind1, kind2;
10661 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010662 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010663
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010664 kind1 = PyUnicode_KIND(str1);
10665 kind2 = PyUnicode_KIND(str2);
10666 data1 = PyUnicode_DATA(str1);
10667 data2 = PyUnicode_DATA(str2);
10668 len1 = PyUnicode_GET_LENGTH(str1);
10669 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010670 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010671
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010672 switch(kind1) {
10673 case PyUnicode_1BYTE_KIND:
10674 {
10675 switch(kind2) {
10676 case PyUnicode_1BYTE_KIND:
10677 {
10678 int cmp = memcmp(data1, data2, len);
10679 /* normalize result of memcmp() into the range [-1; 1] */
10680 if (cmp < 0)
10681 return -1;
10682 if (cmp > 0)
10683 return 1;
10684 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010685 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010686 case PyUnicode_2BYTE_KIND:
10687 COMPARE(Py_UCS1, Py_UCS2);
10688 break;
10689 case PyUnicode_4BYTE_KIND:
10690 COMPARE(Py_UCS1, Py_UCS4);
10691 break;
10692 default:
10693 assert(0);
10694 }
10695 break;
10696 }
10697 case PyUnicode_2BYTE_KIND:
10698 {
10699 switch(kind2) {
10700 case PyUnicode_1BYTE_KIND:
10701 COMPARE(Py_UCS2, Py_UCS1);
10702 break;
10703 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010704 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010705 COMPARE(Py_UCS2, Py_UCS2);
10706 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010707 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010708 case PyUnicode_4BYTE_KIND:
10709 COMPARE(Py_UCS2, Py_UCS4);
10710 break;
10711 default:
10712 assert(0);
10713 }
10714 break;
10715 }
10716 case PyUnicode_4BYTE_KIND:
10717 {
10718 switch(kind2) {
10719 case PyUnicode_1BYTE_KIND:
10720 COMPARE(Py_UCS4, Py_UCS1);
10721 break;
10722 case PyUnicode_2BYTE_KIND:
10723 COMPARE(Py_UCS4, Py_UCS2);
10724 break;
10725 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010726 {
10727#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10728 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10729 /* normalize result of wmemcmp() into the range [-1; 1] */
10730 if (cmp < 0)
10731 return -1;
10732 if (cmp > 0)
10733 return 1;
10734#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010735 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010736#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010737 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010738 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010739 default:
10740 assert(0);
10741 }
10742 break;
10743 }
10744 default:
10745 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010746 }
10747
Victor Stinner770e19e2012-10-04 22:59:45 +020010748 if (len1 == len2)
10749 return 0;
10750 if (len1 < len2)
10751 return -1;
10752 else
10753 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010754
10755#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010756}
10757
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010758Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010759unicode_compare_eq(PyObject *str1, PyObject *str2)
10760{
10761 int kind;
10762 void *data1, *data2;
10763 Py_ssize_t len;
10764 int cmp;
10765
Victor Stinnere5567ad2012-10-23 02:48:49 +020010766 len = PyUnicode_GET_LENGTH(str1);
10767 if (PyUnicode_GET_LENGTH(str2) != len)
10768 return 0;
10769 kind = PyUnicode_KIND(str1);
10770 if (PyUnicode_KIND(str2) != kind)
10771 return 0;
10772 data1 = PyUnicode_DATA(str1);
10773 data2 = PyUnicode_DATA(str2);
10774
10775 cmp = memcmp(data1, data2, len * kind);
10776 return (cmp == 0);
10777}
10778
10779
Alexander Belopolsky40018472011-02-26 01:02:56 +000010780int
10781PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10784 if (PyUnicode_READY(left) == -1 ||
10785 PyUnicode_READY(right) == -1)
10786 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010787
10788 /* a string is equal to itself */
10789 if (left == right)
10790 return 0;
10791
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010792 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010793 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010794 PyErr_Format(PyExc_TypeError,
10795 "Can't compare %.100s and %.100s",
10796 left->ob_type->tp_name,
10797 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 return -1;
10799}
10800
Martin v. Löwis5b222132007-06-10 09:51:05 +000010801int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010802_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10803{
10804 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10805 if (right_str == NULL)
10806 return -1;
10807 return PyUnicode_Compare(left, right_str);
10808}
10809
10810int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010811PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010813 Py_ssize_t i;
10814 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 Py_UCS4 chr;
10816
Victor Stinner910337b2011-10-03 03:20:16 +020010817 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 if (PyUnicode_READY(uni) == -1)
10819 return -1;
10820 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010821 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010822 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010823 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010824 size_t len, len2 = strlen(str);
10825 int cmp;
10826
10827 len = Py_MIN(len1, len2);
10828 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010829 if (cmp != 0) {
10830 if (cmp < 0)
10831 return -1;
10832 else
10833 return 1;
10834 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010835 if (len1 > len2)
10836 return 1; /* uni is longer */
10837 if (len2 > len1)
10838 return -1; /* str is longer */
10839 return 0;
10840 }
10841 else {
10842 void *data = PyUnicode_DATA(uni);
10843 /* Compare Unicode string and source character set string */
10844 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10845 if (chr != str[i])
10846 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10847 /* This check keeps Python strings that end in '\0' from comparing equal
10848 to C strings identical up to that point. */
10849 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10850 return 1; /* uni is longer */
10851 if (str[i])
10852 return -1; /* str is longer */
10853 return 0;
10854 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010855}
10856
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010857
Benjamin Peterson29060642009-01-31 22:14:21 +000010858#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010859 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010860
Alexander Belopolsky40018472011-02-26 01:02:56 +000010861PyObject *
10862PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010863{
10864 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010865 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010866
Victor Stinnere5567ad2012-10-23 02:48:49 +020010867 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10868 Py_RETURN_NOTIMPLEMENTED;
10869
10870 if (PyUnicode_READY(left) == -1 ||
10871 PyUnicode_READY(right) == -1)
10872 return NULL;
10873
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010874 if (left == right) {
10875 switch (op) {
10876 case Py_EQ:
10877 case Py_LE:
10878 case Py_GE:
10879 /* a string is equal to itself */
10880 v = Py_True;
10881 break;
10882 case Py_NE:
10883 case Py_LT:
10884 case Py_GT:
10885 v = Py_False;
10886 break;
10887 default:
10888 PyErr_BadArgument();
10889 return NULL;
10890 }
10891 }
10892 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010893 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010894 result ^= (op == Py_NE);
10895 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010896 }
10897 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010898 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010899
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010900 /* Convert the return value to a Boolean */
10901 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010902 case Py_LE:
10903 v = TEST_COND(result <= 0);
10904 break;
10905 case Py_GE:
10906 v = TEST_COND(result >= 0);
10907 break;
10908 case Py_LT:
10909 v = TEST_COND(result == -1);
10910 break;
10911 case Py_GT:
10912 v = TEST_COND(result == 1);
10913 break;
10914 default:
10915 PyErr_BadArgument();
10916 return NULL;
10917 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010918 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010919 Py_INCREF(v);
10920 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010921}
10922
Alexander Belopolsky40018472011-02-26 01:02:56 +000010923int
10924PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010925{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010926 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010927 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010928 void *buf1, *buf2;
10929 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010930 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010931
10932 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010933 sub = PyUnicode_FromObject(element);
10934 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010935 PyErr_Format(PyExc_TypeError,
10936 "'in <string>' requires string as left operand, not %s",
10937 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010938 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010939 }
10940
Thomas Wouters477c8d52006-05-27 19:21:47 +000010941 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010942 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010943 Py_DECREF(sub);
10944 return -1;
10945 }
10946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 kind1 = PyUnicode_KIND(str);
10948 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949 buf1 = PyUnicode_DATA(str);
10950 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010951 if (kind2 != kind1) {
10952 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010953 Py_DECREF(sub);
10954 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010955 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010956 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010957 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 if (!buf2) {
10960 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010961 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 return -1;
10963 }
10964 len1 = PyUnicode_GET_LENGTH(str);
10965 len2 = PyUnicode_GET_LENGTH(sub);
10966
Victor Stinner77282cb2013-04-14 19:22:47 +020010967 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 case PyUnicode_1BYTE_KIND:
10969 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10970 break;
10971 case PyUnicode_2BYTE_KIND:
10972 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10973 break;
10974 case PyUnicode_4BYTE_KIND:
10975 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10976 break;
10977 default:
10978 result = -1;
10979 assert(0);
10980 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010981
10982 Py_DECREF(str);
10983 Py_DECREF(sub);
10984
Victor Stinner77282cb2013-04-14 19:22:47 +020010985 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 PyMem_Free(buf2);
10987
Guido van Rossum403d68b2000-03-13 15:55:09 +000010988 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010989}
10990
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991/* Concat to string or Unicode object giving a new Unicode object. */
10992
Alexander Belopolsky40018472011-02-26 01:02:56 +000010993PyObject *
10994PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010997 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010998 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999
11000 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011003 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011006 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007
11008 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011009 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011010 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011011 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011013 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011014 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 }
11017
Victor Stinner488fa492011-12-12 00:01:39 +010011018 u_len = PyUnicode_GET_LENGTH(u);
11019 v_len = PyUnicode_GET_LENGTH(v);
11020 if (u_len > PY_SSIZE_T_MAX - v_len) {
11021 PyErr_SetString(PyExc_OverflowError,
11022 "strings are too large to concat");
11023 goto onError;
11024 }
11025 new_len = u_len + v_len;
11026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011027 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011028 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011029 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011030
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011032 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011034 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011035 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11036 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011037 Py_DECREF(u);
11038 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011039 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011040 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 Py_XDECREF(u);
11044 Py_XDECREF(v);
11045 return NULL;
11046}
11047
Walter Dörwald1ab83302007-05-18 17:15:44 +000011048void
Victor Stinner23e56682011-10-03 03:54:37 +020011049PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011050{
Victor Stinner23e56682011-10-03 03:54:37 +020011051 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011052 Py_UCS4 maxchar, maxchar2;
11053 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011054
11055 if (p_left == NULL) {
11056 if (!PyErr_Occurred())
11057 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011058 return;
11059 }
Victor Stinner23e56682011-10-03 03:54:37 +020011060 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011061 if (right == NULL || left == NULL
11062 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011063 if (!PyErr_Occurred())
11064 PyErr_BadInternalCall();
11065 goto error;
11066 }
11067
Benjamin Petersonbac79492012-01-14 13:34:47 -050011068 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011069 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011070 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011071 goto error;
11072
Victor Stinner488fa492011-12-12 00:01:39 +010011073 /* Shortcuts */
11074 if (left == unicode_empty) {
11075 Py_DECREF(left);
11076 Py_INCREF(right);
11077 *p_left = right;
11078 return;
11079 }
11080 if (right == unicode_empty)
11081 return;
11082
11083 left_len = PyUnicode_GET_LENGTH(left);
11084 right_len = PyUnicode_GET_LENGTH(right);
11085 if (left_len > PY_SSIZE_T_MAX - right_len) {
11086 PyErr_SetString(PyExc_OverflowError,
11087 "strings are too large to concat");
11088 goto error;
11089 }
11090 new_len = left_len + right_len;
11091
11092 if (unicode_modifiable(left)
11093 && PyUnicode_CheckExact(right)
11094 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011095 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11096 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011097 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011098 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011099 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11100 {
11101 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011102 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011103 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011104
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011105 /* copy 'right' into the newly allocated area of 'left' */
11106 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011107 }
Victor Stinner488fa492011-12-12 00:01:39 +010011108 else {
11109 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11110 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011111 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011112
Victor Stinner488fa492011-12-12 00:01:39 +010011113 /* Concat the two Unicode strings */
11114 res = PyUnicode_New(new_len, maxchar);
11115 if (res == NULL)
11116 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011117 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11118 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011119 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011120 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011121 }
11122 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011123 return;
11124
11125error:
Victor Stinner488fa492011-12-12 00:01:39 +010011126 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011127}
11128
11129void
11130PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011132 PyUnicode_Append(pleft, right);
11133 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011134}
11135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011136PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011139Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011140string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011141interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142
11143static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011144unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011146 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011147 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011148 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 int kind1, kind2, kind;
11151 void *buf1, *buf2;
11152 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
Jesus Ceaac451502011-04-20 17:09:23 +020011154 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11155 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011156 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 kind1 = PyUnicode_KIND(self);
11159 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011160 if (kind2 > kind1) {
11161 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011162 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011163 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011164 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011165 buf1 = PyUnicode_DATA(self);
11166 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011168 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169 if (!buf2) {
11170 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 return NULL;
11172 }
11173 len1 = PyUnicode_GET_LENGTH(self);
11174 len2 = PyUnicode_GET_LENGTH(substring);
11175
11176 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011177 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 case PyUnicode_1BYTE_KIND:
11179 iresult = ucs1lib_count(
11180 ((Py_UCS1*)buf1) + start, end - start,
11181 buf2, len2, PY_SSIZE_T_MAX
11182 );
11183 break;
11184 case PyUnicode_2BYTE_KIND:
11185 iresult = ucs2lib_count(
11186 ((Py_UCS2*)buf1) + start, end - start,
11187 buf2, len2, PY_SSIZE_T_MAX
11188 );
11189 break;
11190 case PyUnicode_4BYTE_KIND:
11191 iresult = ucs4lib_count(
11192 ((Py_UCS4*)buf1) + start, end - start,
11193 buf2, len2, PY_SSIZE_T_MAX
11194 );
11195 break;
11196 default:
11197 assert(0); iresult = 0;
11198 }
11199
11200 result = PyLong_FromSsize_t(iresult);
11201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 if (kind2 != kind)
11203 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011206
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 return result;
11208}
11209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011210PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011211 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011213Encode S using the codec registered for encoding. Default encoding\n\
11214is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011215handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011216a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11217'xmlcharrefreplace' as well as any other name registered with\n\
11218codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
11220static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011221unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011223 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 char *encoding = NULL;
11225 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011226
Benjamin Peterson308d6372009-09-18 21:42:35 +000011227 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11228 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011230 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011231}
11232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011233PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011234 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235\n\
11236Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011237If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
11239static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011240unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011242 Py_ssize_t i, j, line_pos, src_len, incr;
11243 Py_UCS4 ch;
11244 PyObject *u;
11245 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011246 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011249 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250
Ezio Melotti745d54d2013-11-16 19:10:57 +020011251 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11252 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254
Antoine Pitrou22425222011-10-04 19:10:51 +020011255 if (PyUnicode_READY(self) == -1)
11256 return NULL;
11257
Thomas Wouters7e474022000-07-16 12:04:32 +000011258 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011259 src_len = PyUnicode_GET_LENGTH(self);
11260 i = j = line_pos = 0;
11261 kind = PyUnicode_KIND(self);
11262 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011263 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011264 for (; i < src_len; i++) {
11265 ch = PyUnicode_READ(kind, src_data, i);
11266 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011267 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011268 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011270 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011271 goto overflow;
11272 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011274 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011277 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 goto overflow;
11279 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 if (ch == '\n' || ch == '\r')
11282 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011285 if (!found)
11286 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011287
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011289 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290 if (!u)
11291 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
Antoine Pitroue71d5742011-10-04 15:55:09 +020011294 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Antoine Pitroue71d5742011-10-04 15:55:09 +020011296 for (; i < src_len; i++) {
11297 ch = PyUnicode_READ(kind, src_data, i);
11298 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011299 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011300 incr = tabsize - (line_pos % tabsize);
11301 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011302 FILL(kind, dest_data, ' ', j, incr);
11303 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011305 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011306 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011307 line_pos++;
11308 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011309 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011310 if (ch == '\n' || ch == '\r')
11311 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011313 }
11314 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011315 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011316
Antoine Pitroue71d5742011-10-04 15:55:09 +020011317 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011318 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11319 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320}
11321
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011322PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011323 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324\n\
11325Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011326such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327arguments start and end are interpreted as in slice notation.\n\
11328\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011329Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
11331static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011334 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011335 Py_ssize_t start;
11336 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011337 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338
Jesus Ceaac451502011-04-20 17:09:23 +020011339 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11340 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
Christian Heimesd47802e2013-06-29 21:33:36 +020011343 if (PyUnicode_READY(self) == -1) {
11344 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011346 }
11347 if (PyUnicode_READY(substring) == -1) {
11348 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011349 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011350 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351
Victor Stinner7931d9a2011-11-04 00:22:48 +010011352 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
11354 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (result == -2)
11357 return NULL;
11358
Christian Heimes217cfd12007-12-02 14:31:20 +000011359 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360}
11361
11362static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011363unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011365 void *data;
11366 enum PyUnicode_Kind kind;
11367 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011368
11369 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11370 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011372 }
11373 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11374 PyErr_SetString(PyExc_IndexError, "string index out of range");
11375 return NULL;
11376 }
11377 kind = PyUnicode_KIND(self);
11378 data = PyUnicode_DATA(self);
11379 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011380 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381}
11382
Guido van Rossumc2504932007-09-18 19:42:40 +000011383/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011384 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011385static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011386unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387{
Guido van Rossumc2504932007-09-18 19:42:40 +000011388 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011389 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011390
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011391#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011392 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011393#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011394 if (_PyUnicode_HASH(self) != -1)
11395 return _PyUnicode_HASH(self);
11396 if (PyUnicode_READY(self) == -1)
11397 return -1;
11398 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011399 /*
11400 We make the hash of the empty string be 0, rather than using
11401 (prefix ^ suffix), since this slightly obfuscates the hash secret
11402 */
11403 if (len == 0) {
11404 _PyUnicode_HASH(self) = 0;
11405 return 0;
11406 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011407 x = _Py_HashBytes(PyUnicode_DATA(self),
11408 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011410 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
11418static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011421 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011422 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011423 Py_ssize_t start;
11424 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
Jesus Ceaac451502011-04-20 17:09:23 +020011426 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11427 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Christian Heimesd47a0452013-06-29 21:21:37 +020011430 if (PyUnicode_READY(self) == -1) {
11431 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011433 }
11434 if (PyUnicode_READY(substring) == -1) {
11435 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011437 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438
Victor Stinner7931d9a2011-11-04 00:22:48 +010011439 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
11441 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011443 if (result == -2)
11444 return NULL;
11445
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446 if (result < 0) {
11447 PyErr_SetString(PyExc_ValueError, "substring not found");
11448 return NULL;
11449 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011450
Christian Heimes217cfd12007-12-02 14:31:20 +000011451 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011457Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011458at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
11460static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011461unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 Py_ssize_t i, length;
11464 int kind;
11465 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 int cased;
11467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (PyUnicode_READY(self) == -1)
11469 return NULL;
11470 length = PyUnicode_GET_LENGTH(self);
11471 kind = PyUnicode_KIND(self);
11472 data = PyUnicode_DATA(self);
11473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (length == 1)
11476 return PyBool_FromLong(
11477 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011482
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 for (i = 0; i < length; i++) {
11485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011486
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11488 return PyBool_FromLong(0);
11489 else if (!cased && Py_UNICODE_ISLOWER(ch))
11490 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493}
11494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011495PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011498Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011499at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500
11501static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011502unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 Py_ssize_t i, length;
11505 int kind;
11506 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507 int cased;
11508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 if (PyUnicode_READY(self) == -1)
11510 return NULL;
11511 length = PyUnicode_GET_LENGTH(self);
11512 kind = PyUnicode_KIND(self);
11513 data = PyUnicode_DATA(self);
11514
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 if (length == 1)
11517 return PyBool_FromLong(
11518 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011520 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011523
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 for (i = 0; i < length; i++) {
11526 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011527
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11529 return PyBool_FromLong(0);
11530 else if (!cased && Py_UNICODE_ISUPPER(ch))
11531 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011533 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534}
11535
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011536PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011537 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011539Return True if S is a titlecased string and there is at least one\n\
11540character in S, i.e. upper- and titlecase characters may only\n\
11541follow uncased characters and lowercase characters only cased ones.\n\
11542Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543
11544static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011545unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 Py_ssize_t i, length;
11548 int kind;
11549 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550 int cased, previous_is_cased;
11551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 if (PyUnicode_READY(self) == -1)
11553 return NULL;
11554 length = PyUnicode_GET_LENGTH(self);
11555 kind = PyUnicode_KIND(self);
11556 data = PyUnicode_DATA(self);
11557
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 if (length == 1) {
11560 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11561 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11562 (Py_UNICODE_ISUPPER(ch) != 0));
11563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011565 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011567 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011568
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569 cased = 0;
11570 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 for (i = 0; i < length; i++) {
11572 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011573
Benjamin Peterson29060642009-01-31 22:14:21 +000011574 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11575 if (previous_is_cased)
11576 return PyBool_FromLong(0);
11577 previous_is_cased = 1;
11578 cased = 1;
11579 }
11580 else if (Py_UNICODE_ISLOWER(ch)) {
11581 if (!previous_is_cased)
11582 return PyBool_FromLong(0);
11583 previous_is_cased = 1;
11584 cased = 1;
11585 }
11586 else
11587 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011589 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590}
11591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011592PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011593 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011595Return True if all characters in S are whitespace\n\
11596and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597
11598static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011599unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 Py_ssize_t i, length;
11602 int kind;
11603 void *data;
11604
11605 if (PyUnicode_READY(self) == -1)
11606 return NULL;
11607 length = PyUnicode_GET_LENGTH(self);
11608 kind = PyUnicode_KIND(self);
11609 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (length == 1)
11613 return PyBool_FromLong(
11614 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011616 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 for (i = 0; i < length; i++) {
11621 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011622 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011625 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626}
11627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011628PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011629 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011630\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011631Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011632and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011633
11634static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011635unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 Py_ssize_t i, length;
11638 int kind;
11639 void *data;
11640
11641 if (PyUnicode_READY(self) == -1)
11642 return NULL;
11643 length = PyUnicode_GET_LENGTH(self);
11644 kind = PyUnicode_KIND(self);
11645 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011646
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011647 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 if (length == 1)
11649 return PyBool_FromLong(
11650 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011651
11652 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011653 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 for (i = 0; i < length; i++) {
11657 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011658 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011659 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011660 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661}
11662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011663PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011665\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011666Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011668
11669static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011670unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 int kind;
11673 void *data;
11674 Py_ssize_t len, i;
11675
11676 if (PyUnicode_READY(self) == -1)
11677 return NULL;
11678
11679 kind = PyUnicode_KIND(self);
11680 data = PyUnicode_DATA(self);
11681 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011682
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 if (len == 1) {
11685 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11686 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11687 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011688
11689 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011691 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 for (i = 0; i < len; i++) {
11694 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011695 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011697 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011698 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011699}
11700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011701PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011704Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011705False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706
11707static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011708unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 Py_ssize_t i, length;
11711 int kind;
11712 void *data;
11713
11714 if (PyUnicode_READY(self) == -1)
11715 return NULL;
11716 length = PyUnicode_GET_LENGTH(self);
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 if (length == 1)
11722 return PyBool_FromLong(
11723 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011725 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 for (i = 0; i < length; i++) {
11730 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011733 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734}
11735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011736PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011739Return True if all characters in S are digits\n\
11740and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741
11742static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011743unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 Py_ssize_t i, length;
11746 int kind;
11747 void *data;
11748
11749 if (PyUnicode_READY(self) == -1)
11750 return NULL;
11751 length = PyUnicode_GET_LENGTH(self);
11752 kind = PyUnicode_KIND(self);
11753 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (length == 1) {
11757 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11758 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11759 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011761 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 for (i = 0; i < length; i++) {
11766 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011767 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011768 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011769 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770}
11771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011772PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011775Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011776False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
11778static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011779unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 Py_ssize_t i, length;
11782 int kind;
11783 void *data;
11784
11785 if (PyUnicode_READY(self) == -1)
11786 return NULL;
11787 length = PyUnicode_GET_LENGTH(self);
11788 kind = PyUnicode_KIND(self);
11789 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 if (length == 1)
11793 return PyBool_FromLong(
11794 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011796 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011798 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 for (i = 0; i < length; i++) {
11801 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011803 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011804 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805}
11806
Martin v. Löwis47383402007-08-15 07:32:56 +000011807int
11808PyUnicode_IsIdentifier(PyObject *self)
11809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 int kind;
11811 void *data;
11812 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011813 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815 if (PyUnicode_READY(self) == -1) {
11816 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011817 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 }
11819
11820 /* Special case for empty strings */
11821 if (PyUnicode_GET_LENGTH(self) == 0)
11822 return 0;
11823 kind = PyUnicode_KIND(self);
11824 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011825
11826 /* PEP 3131 says that the first character must be in
11827 XID_Start and subsequent characters in XID_Continue,
11828 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011829 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011830 letters, digits, underscore). However, given the current
11831 definition of XID_Start and XID_Continue, it is sufficient
11832 to check just for these, except that _ must be allowed
11833 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011835 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011836 return 0;
11837
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011838 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011840 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011841 return 1;
11842}
11843
11844PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011846\n\
11847Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011848to the language definition.\n\
11849\n\
11850Use keyword.iskeyword() to test for reserved identifiers\n\
11851such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011852
11853static PyObject*
11854unicode_isidentifier(PyObject *self)
11855{
11856 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11857}
11858
Georg Brandl559e5d72008-06-11 18:37:52 +000011859PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011860 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011861\n\
11862Return True if all characters in S are considered\n\
11863printable in repr() or S is empty, False otherwise.");
11864
11865static PyObject*
11866unicode_isprintable(PyObject *self)
11867{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868 Py_ssize_t i, length;
11869 int kind;
11870 void *data;
11871
11872 if (PyUnicode_READY(self) == -1)
11873 return NULL;
11874 length = PyUnicode_GET_LENGTH(self);
11875 kind = PyUnicode_KIND(self);
11876 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011877
11878 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 if (length == 1)
11880 return PyBool_FromLong(
11881 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 for (i = 0; i < length; i++) {
11884 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011885 Py_RETURN_FALSE;
11886 }
11887 }
11888 Py_RETURN_TRUE;
11889}
11890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011891PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011892 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893\n\
11894Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011895iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896
11897static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011898unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011900 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901}
11902
Martin v. Löwis18e16552006-02-15 17:27:45 +000011903static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011904unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 if (PyUnicode_READY(self) == -1)
11907 return -1;
11908 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909}
11910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011911PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011914Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011915done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916
11917static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011918unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011920 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 Py_UCS4 fillchar = ' ';
11922
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011923 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 return NULL;
11925
Benjamin Petersonbac79492012-01-14 13:34:47 -050011926 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011927 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928
Victor Stinnerc4b49542011-12-11 22:44:26 +010011929 if (PyUnicode_GET_LENGTH(self) >= width)
11930 return unicode_result_unchanged(self);
11931
11932 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933}
11934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011935PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011938Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939
11940static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011941unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011943 if (PyUnicode_READY(self) == -1)
11944 return NULL;
11945 if (PyUnicode_IS_ASCII(self))
11946 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011947 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948}
11949
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950#define LEFTSTRIP 0
11951#define RIGHTSTRIP 1
11952#define BOTHSTRIP 2
11953
11954/* Arrays indexed by above */
11955static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11956
11957#define STRIPNAME(i) (stripformat[i]+3)
11958
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011959/* externally visible for str.strip(unicode) */
11960PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011961_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 void *data;
11964 int kind;
11965 Py_ssize_t i, j, len;
11966 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011967 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11970 return NULL;
11971
11972 kind = PyUnicode_KIND(self);
11973 data = PyUnicode_DATA(self);
11974 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011975 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011976 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11977 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011978 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011979
Benjamin Peterson14339b62009-01-31 16:36:08 +000011980 i = 0;
11981 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011982 while (i < len) {
11983 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11984 if (!BLOOM(sepmask, ch))
11985 break;
11986 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11987 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 i++;
11989 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011990 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011991
Benjamin Peterson14339b62009-01-31 16:36:08 +000011992 j = len;
11993 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011994 j--;
11995 while (j >= i) {
11996 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11997 if (!BLOOM(sepmask, ch))
11998 break;
11999 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12000 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012001 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012002 }
12003
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012005 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012006
Victor Stinner7931d9a2011-11-04 00:22:48 +010012007 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008}
12009
12010PyObject*
12011PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12012{
12013 unsigned char *data;
12014 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012015 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012016
Victor Stinnerde636f32011-10-01 03:55:54 +020012017 if (PyUnicode_READY(self) == -1)
12018 return NULL;
12019
Victor Stinner684d5fd2012-05-03 02:32:34 +020012020 length = PyUnicode_GET_LENGTH(self);
12021 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012022
Victor Stinner684d5fd2012-05-03 02:32:34 +020012023 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012024 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025
Victor Stinnerde636f32011-10-01 03:55:54 +020012026 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012027 PyErr_SetString(PyExc_IndexError, "string index out of range");
12028 return NULL;
12029 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012030 if (start >= length || end < start)
12031 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012032
Victor Stinner684d5fd2012-05-03 02:32:34 +020012033 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012034 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012035 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012036 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012037 }
12038 else {
12039 kind = PyUnicode_KIND(self);
12040 data = PyUnicode_1BYTE_DATA(self);
12041 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012042 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012043 length);
12044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
12047static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012048do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 Py_ssize_t len, i, j;
12051
12052 if (PyUnicode_READY(self) == -1)
12053 return NULL;
12054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012056
Victor Stinnercc7af722013-04-09 22:39:24 +020012057 if (PyUnicode_IS_ASCII(self)) {
12058 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12059
12060 i = 0;
12061 if (striptype != RIGHTSTRIP) {
12062 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012063 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012064 if (!_Py_ascii_whitespace[ch])
12065 break;
12066 i++;
12067 }
12068 }
12069
12070 j = len;
12071 if (striptype != LEFTSTRIP) {
12072 j--;
12073 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012074 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012075 if (!_Py_ascii_whitespace[ch])
12076 break;
12077 j--;
12078 }
12079 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012080 }
12081 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012082 else {
12083 int kind = PyUnicode_KIND(self);
12084 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012085
Victor Stinnercc7af722013-04-09 22:39:24 +020012086 i = 0;
12087 if (striptype != RIGHTSTRIP) {
12088 while (i < len) {
12089 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12090 if (!Py_UNICODE_ISSPACE(ch))
12091 break;
12092 i++;
12093 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012094 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012095
12096 j = len;
12097 if (striptype != LEFTSTRIP) {
12098 j--;
12099 while (j >= i) {
12100 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12101 if (!Py_UNICODE_ISSPACE(ch))
12102 break;
12103 j--;
12104 }
12105 j++;
12106 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012107 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012108
Victor Stinner7931d9a2011-11-04 00:22:48 +010012109 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110}
12111
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012112
12113static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012114do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012115{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012116 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012117
Serhiy Storchakac6792272013-10-19 21:03:34 +030012118 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012119 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012120
Benjamin Peterson14339b62009-01-31 16:36:08 +000012121 if (sep != NULL && sep != Py_None) {
12122 if (PyUnicode_Check(sep))
12123 return _PyUnicode_XStrip(self, striptype, sep);
12124 else {
12125 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012126 "%s arg must be None or str",
12127 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012128 return NULL;
12129 }
12130 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
Benjamin Peterson14339b62009-01-31 16:36:08 +000012132 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012133}
12134
12135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012136PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012137 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012138\n\
12139Return a copy of the string S with leading and trailing\n\
12140whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012141If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012142
12143static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012144unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 if (PyTuple_GET_SIZE(args) == 0)
12147 return do_strip(self, BOTHSTRIP); /* Common case */
12148 else
12149 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012150}
12151
12152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012153PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012155\n\
12156Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012157If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012158
12159static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 if (PyTuple_GET_SIZE(args) == 0)
12163 return do_strip(self, LEFTSTRIP); /* Common case */
12164 else
12165 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166}
12167
12168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012169PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012170 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012171\n\
12172Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012173If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012174
12175static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012176unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012178 if (PyTuple_GET_SIZE(args) == 0)
12179 return do_strip(self, RIGHTSTRIP); /* Common case */
12180 else
12181 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012182}
12183
12184
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012186unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012188 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190
Serhiy Storchaka05997252013-01-26 12:14:02 +020012191 if (len < 1)
12192 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193
Victor Stinnerc4b49542011-12-11 22:44:26 +010012194 /* no repeat, return original string */
12195 if (len == 1)
12196 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012197
Benjamin Petersonbac79492012-01-14 13:34:47 -050012198 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012199 return NULL;
12200
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012201 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012202 PyErr_SetString(PyExc_OverflowError,
12203 "repeated string is too long");
12204 return NULL;
12205 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012207
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012208 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209 if (!u)
12210 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012211 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 if (PyUnicode_GET_LENGTH(str) == 1) {
12214 const int kind = PyUnicode_KIND(str);
12215 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012216 if (kind == PyUnicode_1BYTE_KIND) {
12217 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012218 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012219 }
12220 else if (kind == PyUnicode_2BYTE_KIND) {
12221 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012222 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012223 ucs2[n] = fill_char;
12224 } else {
12225 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12226 assert(kind == PyUnicode_4BYTE_KIND);
12227 for (n = 0; n < len; ++n)
12228 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012230 }
12231 else {
12232 /* number of characters copied this far */
12233 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012234 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 char *to = (char *) PyUnicode_DATA(u);
12236 Py_MEMCPY(to, PyUnicode_DATA(str),
12237 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012238 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 n = (done <= nchars-done) ? done : nchars-done;
12240 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012241 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012242 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243 }
12244
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012245 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012246 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247}
12248
Alexander Belopolsky40018472011-02-26 01:02:56 +000012249PyObject *
12250PyUnicode_Replace(PyObject *obj,
12251 PyObject *subobj,
12252 PyObject *replobj,
12253 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
12255 PyObject *self;
12256 PyObject *str1;
12257 PyObject *str2;
12258 PyObject *result;
12259
12260 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012261 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012264 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 Py_DECREF(self);
12266 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267 }
12268 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012269 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012270 Py_DECREF(self);
12271 Py_DECREF(str1);
12272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012274 if (PyUnicode_READY(self) == -1 ||
12275 PyUnicode_READY(str1) == -1 ||
12276 PyUnicode_READY(str2) == -1)
12277 result = NULL;
12278 else
12279 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280 Py_DECREF(self);
12281 Py_DECREF(str1);
12282 Py_DECREF(str2);
12283 return result;
12284}
12285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012286PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012287 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288\n\
12289Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012290old replaced by new. If the optional argument count is\n\
12291given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292
12293static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 PyObject *str1;
12297 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012298 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299 PyObject *result;
12300
Martin v. Löwis18e16552006-02-15 17:27:45 +000012301 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012303 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012304 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012306 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 return NULL;
12308 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012309 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012310 Py_DECREF(str1);
12311 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012312 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012313 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12314 result = NULL;
12315 else
12316 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318 Py_DECREF(str1);
12319 Py_DECREF(str2);
12320 return result;
12321}
12322
Alexander Belopolsky40018472011-02-26 01:02:56 +000012323static PyObject *
12324unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012326 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 Py_ssize_t isize;
12328 Py_ssize_t osize, squote, dquote, i, o;
12329 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012330 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012334 return NULL;
12335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 isize = PyUnicode_GET_LENGTH(unicode);
12337 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 /* Compute length of output, quote characters, and
12340 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012341 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 max = 127;
12343 squote = dquote = 0;
12344 ikind = PyUnicode_KIND(unicode);
12345 for (i = 0; i < isize; i++) {
12346 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012347 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012349 case '\'': squote++; break;
12350 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012352 incr = 2;
12353 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 default:
12355 /* Fast-path ASCII */
12356 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012357 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012359 ;
12360 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012363 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012365 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012367 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012368 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012369 if (osize > PY_SSIZE_T_MAX - incr) {
12370 PyErr_SetString(PyExc_OverflowError,
12371 "string is too long to generate repr");
12372 return NULL;
12373 }
12374 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 }
12376
12377 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012378 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012380 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 if (dquote)
12382 /* Both squote and dquote present. Use squote,
12383 and escape them */
12384 osize += squote;
12385 else
12386 quote = '"';
12387 }
Victor Stinner55c08782013-04-14 18:45:39 +020012388 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012389
12390 repr = PyUnicode_New(osize, max);
12391 if (repr == NULL)
12392 return NULL;
12393 okind = PyUnicode_KIND(repr);
12394 odata = PyUnicode_DATA(repr);
12395
12396 PyUnicode_WRITE(okind, odata, 0, quote);
12397 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012398 if (unchanged) {
12399 _PyUnicode_FastCopyCharacters(repr, 1,
12400 unicode, 0,
12401 isize);
12402 }
12403 else {
12404 for (i = 0, o = 1; i < isize; i++) {
12405 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012406
Victor Stinner55c08782013-04-14 18:45:39 +020012407 /* Escape quotes and backslashes */
12408 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012409 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012411 continue;
12412 }
12413
12414 /* Map special whitespace to '\t', \n', '\r' */
12415 if (ch == '\t') {
12416 PyUnicode_WRITE(okind, odata, o++, '\\');
12417 PyUnicode_WRITE(okind, odata, o++, 't');
12418 }
12419 else if (ch == '\n') {
12420 PyUnicode_WRITE(okind, odata, o++, '\\');
12421 PyUnicode_WRITE(okind, odata, o++, 'n');
12422 }
12423 else if (ch == '\r') {
12424 PyUnicode_WRITE(okind, odata, o++, '\\');
12425 PyUnicode_WRITE(okind, odata, o++, 'r');
12426 }
12427
12428 /* Map non-printable US ASCII to '\xhh' */
12429 else if (ch < ' ' || ch == 0x7F) {
12430 PyUnicode_WRITE(okind, odata, o++, '\\');
12431 PyUnicode_WRITE(okind, odata, o++, 'x');
12432 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12433 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12434 }
12435
12436 /* Copy ASCII characters as-is */
12437 else if (ch < 0x7F) {
12438 PyUnicode_WRITE(okind, odata, o++, ch);
12439 }
12440
12441 /* Non-ASCII characters */
12442 else {
12443 /* Map Unicode whitespace and control characters
12444 (categories Z* and C* except ASCII space)
12445 */
12446 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12447 PyUnicode_WRITE(okind, odata, o++, '\\');
12448 /* Map 8-bit characters to '\xhh' */
12449 if (ch <= 0xff) {
12450 PyUnicode_WRITE(okind, odata, o++, 'x');
12451 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12452 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12453 }
12454 /* Map 16-bit characters to '\uxxxx' */
12455 else if (ch <= 0xffff) {
12456 PyUnicode_WRITE(okind, odata, o++, 'u');
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12461 }
12462 /* Map 21-bit characters to '\U00xxxxxx' */
12463 else {
12464 PyUnicode_WRITE(okind, odata, o++, 'U');
12465 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12466 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12467 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12469 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12470 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12471 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12472 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12473 }
12474 }
12475 /* Copy characters as-is */
12476 else {
12477 PyUnicode_WRITE(okind, odata, o++, ch);
12478 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012479 }
12480 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012483 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012484 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485}
12486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012487PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489\n\
12490Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012491such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492arguments start and end are interpreted as in slice notation.\n\
12493\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012494Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495
12496static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012499 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012500 Py_ssize_t start;
12501 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012502 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
Jesus Ceaac451502011-04-20 17:09:23 +020012504 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12505 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012506 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507
Christian Heimesea71a522013-06-29 21:17:34 +020012508 if (PyUnicode_READY(self) == -1) {
12509 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012510 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012511 }
12512 if (PyUnicode_READY(substring) == -1) {
12513 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012514 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012515 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012516
Victor Stinner7931d9a2011-11-04 00:22:48 +010012517 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
12519 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012521 if (result == -2)
12522 return NULL;
12523
Christian Heimes217cfd12007-12-02 14:31:20 +000012524 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525}
12526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012527PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012530Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531
12532static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012535 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012536 Py_ssize_t start;
12537 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012538 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
Jesus Ceaac451502011-04-20 17:09:23 +020012540 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12541 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012542 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543
Christian Heimesea71a522013-06-29 21:17:34 +020012544 if (PyUnicode_READY(self) == -1) {
12545 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012547 }
12548 if (PyUnicode_READY(substring) == -1) {
12549 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552
Victor Stinner7931d9a2011-11-04 00:22:48 +010012553 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554
12555 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 if (result == -2)
12558 return NULL;
12559
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560 if (result < 0) {
12561 PyErr_SetString(PyExc_ValueError, "substring not found");
12562 return NULL;
12563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564
Christian Heimes217cfd12007-12-02 14:31:20 +000012565 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012566}
12567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012568PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012569 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012571Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012572done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573
12574static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012575unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012577 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 Py_UCS4 fillchar = ' ';
12579
Victor Stinnere9a29352011-10-01 02:14:59 +020012580 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012582
Benjamin Petersonbac79492012-01-14 13:34:47 -050012583 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584 return NULL;
12585
Victor Stinnerc4b49542011-12-11 22:44:26 +010012586 if (PyUnicode_GET_LENGTH(self) >= width)
12587 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588
Victor Stinnerc4b49542011-12-11 22:44:26 +010012589 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590}
12591
Alexander Belopolsky40018472011-02-26 01:02:56 +000012592PyObject *
12593PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594{
12595 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012596
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597 s = PyUnicode_FromObject(s);
12598 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012599 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012600 if (sep != NULL) {
12601 sep = PyUnicode_FromObject(sep);
12602 if (sep == NULL) {
12603 Py_DECREF(s);
12604 return NULL;
12605 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606 }
12607
Victor Stinner9310abb2011-10-05 00:59:23 +020012608 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
12610 Py_DECREF(s);
12611 Py_XDECREF(sep);
12612 return result;
12613}
12614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012615PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012616 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617\n\
12618Return a list of the words in S, using sep as the\n\
12619delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012620splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012621whitespace string is a separator and empty strings are\n\
12622removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
12624static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012625unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012627 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012629 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012631 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12632 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633 return NULL;
12634
12635 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012636 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012638 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012639 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012640 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641}
12642
Thomas Wouters477c8d52006-05-27 19:21:47 +000012643PyObject *
12644PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12645{
12646 PyObject* str_obj;
12647 PyObject* sep_obj;
12648 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 int kind1, kind2, kind;
12650 void *buf1 = NULL, *buf2 = NULL;
12651 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012652
12653 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012654 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012655 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012656 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012657 if (!sep_obj) {
12658 Py_DECREF(str_obj);
12659 return NULL;
12660 }
12661 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12662 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012663 Py_DECREF(str_obj);
12664 return NULL;
12665 }
12666
Victor Stinner14f8f022011-10-05 20:58:25 +020012667 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012669 kind = Py_MAX(kind1, kind2);
12670 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012672 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012673 if (!buf1)
12674 goto onError;
12675 buf2 = PyUnicode_DATA(sep_obj);
12676 if (kind2 != kind)
12677 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12678 if (!buf2)
12679 goto onError;
12680 len1 = PyUnicode_GET_LENGTH(str_obj);
12681 len2 = PyUnicode_GET_LENGTH(sep_obj);
12682
Benjamin Petersonead6b532011-12-20 17:23:42 -060012683 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012685 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12686 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12687 else
12688 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 break;
12690 case PyUnicode_2BYTE_KIND:
12691 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12692 break;
12693 case PyUnicode_4BYTE_KIND:
12694 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12695 break;
12696 default:
12697 assert(0);
12698 out = 0;
12699 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700
12701 Py_DECREF(sep_obj);
12702 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 if (kind1 != kind)
12704 PyMem_Free(buf1);
12705 if (kind2 != kind)
12706 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707
12708 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 onError:
12710 Py_DECREF(sep_obj);
12711 Py_DECREF(str_obj);
12712 if (kind1 != kind && buf1)
12713 PyMem_Free(buf1);
12714 if (kind2 != kind && buf2)
12715 PyMem_Free(buf2);
12716 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012717}
12718
12719
12720PyObject *
12721PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12722{
12723 PyObject* str_obj;
12724 PyObject* sep_obj;
12725 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 int kind1, kind2, kind;
12727 void *buf1 = NULL, *buf2 = NULL;
12728 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729
12730 str_obj = PyUnicode_FromObject(str_in);
12731 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012732 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012733 sep_obj = PyUnicode_FromObject(sep_in);
12734 if (!sep_obj) {
12735 Py_DECREF(str_obj);
12736 return NULL;
12737 }
12738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739 kind1 = PyUnicode_KIND(str_in);
12740 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012741 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 buf1 = PyUnicode_DATA(str_in);
12743 if (kind1 != kind)
12744 buf1 = _PyUnicode_AsKind(str_in, kind);
12745 if (!buf1)
12746 goto onError;
12747 buf2 = PyUnicode_DATA(sep_obj);
12748 if (kind2 != kind)
12749 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12750 if (!buf2)
12751 goto onError;
12752 len1 = PyUnicode_GET_LENGTH(str_obj);
12753 len2 = PyUnicode_GET_LENGTH(sep_obj);
12754
Benjamin Petersonead6b532011-12-20 17:23:42 -060012755 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012757 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12758 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12759 else
12760 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 break;
12762 case PyUnicode_2BYTE_KIND:
12763 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12764 break;
12765 case PyUnicode_4BYTE_KIND:
12766 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12767 break;
12768 default:
12769 assert(0);
12770 out = 0;
12771 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012772
12773 Py_DECREF(sep_obj);
12774 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012775 if (kind1 != kind)
12776 PyMem_Free(buf1);
12777 if (kind2 != kind)
12778 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012779
12780 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012781 onError:
12782 Py_DECREF(sep_obj);
12783 Py_DECREF(str_obj);
12784 if (kind1 != kind && buf1)
12785 PyMem_Free(buf1);
12786 if (kind2 != kind && buf2)
12787 PyMem_Free(buf2);
12788 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789}
12790
12791PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012794Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012796found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797
12798static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012799unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800{
Victor Stinner9310abb2011-10-05 00:59:23 +020012801 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802}
12803
12804PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012805 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012806\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012807Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012808the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012809separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012810
12811static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012812unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012813{
Victor Stinner9310abb2011-10-05 00:59:23 +020012814 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815}
12816
Alexander Belopolsky40018472011-02-26 01:02:56 +000012817PyObject *
12818PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012819{
12820 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012821
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012822 s = PyUnicode_FromObject(s);
12823 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012824 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012825 if (sep != NULL) {
12826 sep = PyUnicode_FromObject(sep);
12827 if (sep == NULL) {
12828 Py_DECREF(s);
12829 return NULL;
12830 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012831 }
12832
Victor Stinner9310abb2011-10-05 00:59:23 +020012833 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012834
12835 Py_DECREF(s);
12836 Py_XDECREF(sep);
12837 return result;
12838}
12839
12840PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012841 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012842\n\
12843Return a list of the words in S, using sep as the\n\
12844delimiter string, starting at the end of the string and\n\
12845working to the front. If maxsplit is given, at most maxsplit\n\
12846splits are done. If sep is not specified, any whitespace string\n\
12847is a separator.");
12848
12849static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012850unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012851{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012852 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012853 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012854 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012855
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012856 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12857 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012858 return NULL;
12859
12860 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012862 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012863 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012864 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012865 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012866}
12867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012868PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012869 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870\n\
12871Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012872Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012873is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874
12875static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012876unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012878 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012879 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012881 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12882 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883 return NULL;
12884
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012885 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886}
12887
12888static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012889PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012891 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892}
12893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012894PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896\n\
12897Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012898and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899
12900static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012901unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012903 if (PyUnicode_READY(self) == -1)
12904 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012905 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906}
12907
Larry Hastings61272b72014-01-07 12:41:53 -080012908/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012909
Larry Hastings31826802013-10-19 00:09:25 -070012910@staticmethod
12911str.maketrans as unicode_maketrans
12912
12913 x: object
12914
12915 y: unicode=NULL
12916
12917 z: unicode=NULL
12918
12919 /
12920
12921Return a translation table usable for str.translate().
12922
12923If there is only one argument, it must be a dictionary mapping Unicode
12924ordinals (integers) or characters to Unicode ordinals, strings or None.
12925Character keys will be then converted to ordinals.
12926If there are two arguments, they must be strings of equal length, and
12927in the resulting dictionary, each character in x will be mapped to the
12928character at the same position in y. If there is a third argument, it
12929must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012930[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012931
12932PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012933"maketrans(x, y=None, z=None, /)\n"
12934"--\n"
12935"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012936"Return a translation table usable for str.translate().\n"
12937"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012938"If there is only one argument, it must be a dictionary mapping Unicode\n"
12939"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12940"Character keys will be then converted to ordinals.\n"
12941"If there are two arguments, they must be strings of equal length, and\n"
12942"in the resulting dictionary, each character in x will be mapped to the\n"
12943"character at the same position in y. If there is a third argument, it\n"
12944"must be a string, whose characters will be mapped to None in the result.");
12945
12946#define UNICODE_MAKETRANS_METHODDEF \
12947 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12948
12949static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012950unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012951
12952static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012953unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012954{
Larry Hastings31826802013-10-19 00:09:25 -070012955 PyObject *return_value = NULL;
12956 PyObject *x;
12957 PyObject *y = NULL;
12958 PyObject *z = NULL;
12959
12960 if (!PyArg_ParseTuple(args,
12961 "O|UU:maketrans",
12962 &x, &y, &z))
12963 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012964 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012965
12966exit:
12967 return return_value;
12968}
12969
12970static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012971unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012972/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012973{
Georg Brandlceee0772007-11-27 23:48:05 +000012974 PyObject *new = NULL, *key, *value;
12975 Py_ssize_t i = 0;
12976 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012977
Georg Brandlceee0772007-11-27 23:48:05 +000012978 new = PyDict_New();
12979 if (!new)
12980 return NULL;
12981 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 int x_kind, y_kind, z_kind;
12983 void *x_data, *y_data, *z_data;
12984
Georg Brandlceee0772007-11-27 23:48:05 +000012985 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012986 if (!PyUnicode_Check(x)) {
12987 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12988 "be a string if there is a second argument");
12989 goto err;
12990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012992 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12993 "arguments must have equal length");
12994 goto err;
12995 }
12996 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 x_kind = PyUnicode_KIND(x);
12998 y_kind = PyUnicode_KIND(y);
12999 x_data = PyUnicode_DATA(x);
13000 y_data = PyUnicode_DATA(y);
13001 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13002 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013003 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013004 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013005 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013006 if (!value) {
13007 Py_DECREF(key);
13008 goto err;
13009 }
Georg Brandlceee0772007-11-27 23:48:05 +000013010 res = PyDict_SetItem(new, key, value);
13011 Py_DECREF(key);
13012 Py_DECREF(value);
13013 if (res < 0)
13014 goto err;
13015 }
13016 /* create entries for deleting chars in z */
13017 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013018 z_kind = PyUnicode_KIND(z);
13019 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013020 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013022 if (!key)
13023 goto err;
13024 res = PyDict_SetItem(new, key, Py_None);
13025 Py_DECREF(key);
13026 if (res < 0)
13027 goto err;
13028 }
13029 }
13030 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013031 int kind;
13032 void *data;
13033
Georg Brandlceee0772007-11-27 23:48:05 +000013034 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013035 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013036 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13037 "to maketrans it must be a dict");
13038 goto err;
13039 }
13040 /* copy entries into the new dict, converting string keys to int keys */
13041 while (PyDict_Next(x, &i, &key, &value)) {
13042 if (PyUnicode_Check(key)) {
13043 /* convert string keys to integer keys */
13044 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013045 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013046 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13047 "table must be of length 1");
13048 goto err;
13049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013050 kind = PyUnicode_KIND(key);
13051 data = PyUnicode_DATA(key);
13052 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013053 if (!newkey)
13054 goto err;
13055 res = PyDict_SetItem(new, newkey, value);
13056 Py_DECREF(newkey);
13057 if (res < 0)
13058 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013059 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013060 /* just keep integer keys */
13061 if (PyDict_SetItem(new, key, value) < 0)
13062 goto err;
13063 } else {
13064 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13065 "be strings or integers");
13066 goto err;
13067 }
13068 }
13069 }
13070 return new;
13071 err:
13072 Py_DECREF(new);
13073 return NULL;
13074}
13075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013076PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013077 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013078\n\
13079Return a copy of the string S, where all characters have been mapped\n\
13080through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013081Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013082Unmapped characters are left untouched. Characters mapped to None\n\
13083are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084
13085static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013086unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013087{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089}
13090
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013091PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013094Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095
13096static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013097unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013099 if (PyUnicode_READY(self) == -1)
13100 return NULL;
13101 if (PyUnicode_IS_ASCII(self))
13102 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013103 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104}
13105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013106PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013109Pad a numeric string S with zeros on the left, to fill a field\n\
13110of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111
13112static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013113unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013115 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013116 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013117 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 int kind;
13119 void *data;
13120 Py_UCS4 chr;
13121
Martin v. Löwis18e16552006-02-15 17:27:45 +000013122 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123 return NULL;
13124
Benjamin Petersonbac79492012-01-14 13:34:47 -050013125 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013126 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127
Victor Stinnerc4b49542011-12-11 22:44:26 +010013128 if (PyUnicode_GET_LENGTH(self) >= width)
13129 return unicode_result_unchanged(self);
13130
13131 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132
13133 u = pad(self, fill, 0, '0');
13134
Walter Dörwald068325e2002-04-15 13:36:47 +000013135 if (u == NULL)
13136 return NULL;
13137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013138 kind = PyUnicode_KIND(u);
13139 data = PyUnicode_DATA(u);
13140 chr = PyUnicode_READ(kind, data, fill);
13141
13142 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 PyUnicode_WRITE(kind, data, 0, chr);
13145 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146 }
13147
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013148 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013149 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151
13152#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013153static PyObject *
13154unicode__decimal2ascii(PyObject *self)
13155{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013157}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158#endif
13159
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013160PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013161 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013163Return True if S starts with the specified prefix, False otherwise.\n\
13164With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013165With optional end, stop comparing S at that position.\n\
13166prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013167
13168static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013169unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013170 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013172 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013173 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013174 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013175 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013176 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177
Jesus Ceaac451502011-04-20 17:09:23 +020013178 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013179 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180 if (PyTuple_Check(subobj)) {
13181 Py_ssize_t i;
13182 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013183 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013184 if (substring == NULL)
13185 return NULL;
13186 result = tailmatch(self, substring, start, end, -1);
13187 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013188 if (result == -1)
13189 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013190 if (result) {
13191 Py_RETURN_TRUE;
13192 }
13193 }
13194 /* nothing matched */
13195 Py_RETURN_FALSE;
13196 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013197 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013198 if (substring == NULL) {
13199 if (PyErr_ExceptionMatches(PyExc_TypeError))
13200 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13201 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013203 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013204 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013206 if (result == -1)
13207 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013208 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209}
13210
13211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013212PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013215Return True if S ends with the specified suffix, False otherwise.\n\
13216With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013217With optional end, stop comparing S at that position.\n\
13218suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219
13220static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013221unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013224 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013225 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013226 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013227 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013228 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013229
Jesus Ceaac451502011-04-20 17:09:23 +020013230 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 if (PyTuple_Check(subobj)) {
13233 Py_ssize_t i;
13234 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013235 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013236 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013237 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013238 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013239 result = tailmatch(self, substring, start, end, +1);
13240 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013241 if (result == -1)
13242 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013243 if (result) {
13244 Py_RETURN_TRUE;
13245 }
13246 }
13247 Py_RETURN_FALSE;
13248 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013249 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013250 if (substring == NULL) {
13251 if (PyErr_ExceptionMatches(PyExc_TypeError))
13252 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13253 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013255 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013256 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013257 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013258 if (result == -1)
13259 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013260 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261}
13262
Victor Stinner202fdca2012-05-07 12:47:02 +020013263Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013264_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013265{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013266 if (!writer->readonly)
13267 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13268 else {
13269 /* Copy-on-write mode: set buffer size to 0 so
13270 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13271 * next write. */
13272 writer->size = 0;
13273 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013274 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13275 writer->data = PyUnicode_DATA(writer->buffer);
13276 writer->kind = PyUnicode_KIND(writer->buffer);
13277}
13278
Victor Stinnerd3f08822012-05-29 12:57:52 +020013279void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013280_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013281{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013282 memset(writer, 0, sizeof(*writer));
13283#ifdef Py_DEBUG
13284 writer->kind = 5; /* invalid kind */
13285#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013286 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013287}
13288
Victor Stinnerd3f08822012-05-29 12:57:52 +020013289int
13290_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13291 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013292{
Victor Stinner6989ba02013-11-18 21:08:39 +010013293#ifdef MS_WINDOWS
13294 /* On Windows, overallocate by 50% is the best factor */
13295# define OVERALLOCATE_FACTOR 2
13296#else
13297 /* On Linux, overallocate by 25% is the best factor */
13298# define OVERALLOCATE_FACTOR 4
13299#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013300 Py_ssize_t newlen;
13301 PyObject *newbuffer;
13302
Victor Stinnerd3f08822012-05-29 12:57:52 +020013303 assert(length > 0);
13304
Victor Stinner202fdca2012-05-07 12:47:02 +020013305 if (length > PY_SSIZE_T_MAX - writer->pos) {
13306 PyErr_NoMemory();
13307 return -1;
13308 }
13309 newlen = writer->pos + length;
13310
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013311 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013312
Victor Stinnerd3f08822012-05-29 12:57:52 +020013313 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013314 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013315 if (writer->overallocate
13316 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13317 /* overallocate to limit the number of realloc() */
13318 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013319 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013320 if (newlen < writer->min_length)
13321 newlen = writer->min_length;
13322
Victor Stinnerd3f08822012-05-29 12:57:52 +020013323 writer->buffer = PyUnicode_New(newlen, maxchar);
13324 if (writer->buffer == NULL)
13325 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013326 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013327 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013328 if (writer->overallocate
13329 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13330 /* overallocate to limit the number of realloc() */
13331 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013332 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013333 if (newlen < writer->min_length)
13334 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013335
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013336 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013337 /* resize + widen */
13338 newbuffer = PyUnicode_New(newlen, maxchar);
13339 if (newbuffer == NULL)
13340 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013341 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13342 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013343 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013344 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013345 }
13346 else {
13347 newbuffer = resize_compact(writer->buffer, newlen);
13348 if (newbuffer == NULL)
13349 return -1;
13350 }
13351 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013352 }
13353 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013354 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013355 newbuffer = PyUnicode_New(writer->size, maxchar);
13356 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013357 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013358 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13359 writer->buffer, 0, writer->pos);
13360 Py_DECREF(writer->buffer);
13361 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013362 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013363 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013364 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013365
13366#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013367}
13368
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013369Py_LOCAL_INLINE(int)
13370_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013371{
13372 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13373 return -1;
13374 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13375 writer->pos++;
13376 return 0;
13377}
13378
13379int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013380_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13381{
13382 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13383}
13384
13385int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013386_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13387{
13388 Py_UCS4 maxchar;
13389 Py_ssize_t len;
13390
13391 if (PyUnicode_READY(str) == -1)
13392 return -1;
13393 len = PyUnicode_GET_LENGTH(str);
13394 if (len == 0)
13395 return 0;
13396 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13397 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013398 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013399 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013400 Py_INCREF(str);
13401 writer->buffer = str;
13402 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013403 writer->pos += len;
13404 return 0;
13405 }
13406 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13407 return -1;
13408 }
13409 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13410 str, 0, len);
13411 writer->pos += len;
13412 return 0;
13413}
13414
Victor Stinnere215d962012-10-06 23:03:36 +020013415int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013416_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13417 Py_ssize_t start, Py_ssize_t end)
13418{
13419 Py_UCS4 maxchar;
13420 Py_ssize_t len;
13421
13422 if (PyUnicode_READY(str) == -1)
13423 return -1;
13424
13425 assert(0 <= start);
13426 assert(end <= PyUnicode_GET_LENGTH(str));
13427 assert(start <= end);
13428
13429 if (end == 0)
13430 return 0;
13431
13432 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13433 return _PyUnicodeWriter_WriteStr(writer, str);
13434
13435 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13436 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13437 else
13438 maxchar = writer->maxchar;
13439 len = end - start;
13440
13441 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13442 return -1;
13443
13444 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13445 str, start, len);
13446 writer->pos += len;
13447 return 0;
13448}
13449
13450int
Victor Stinner4a587072013-11-19 12:54:53 +010013451_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13452 const char *ascii, Py_ssize_t len)
13453{
13454 if (len == -1)
13455 len = strlen(ascii);
13456
13457 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13458
13459 if (writer->buffer == NULL && !writer->overallocate) {
13460 PyObject *str;
13461
13462 str = _PyUnicode_FromASCII(ascii, len);
13463 if (str == NULL)
13464 return -1;
13465
13466 writer->readonly = 1;
13467 writer->buffer = str;
13468 _PyUnicodeWriter_Update(writer);
13469 writer->pos += len;
13470 return 0;
13471 }
13472
13473 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13474 return -1;
13475
13476 switch (writer->kind)
13477 {
13478 case PyUnicode_1BYTE_KIND:
13479 {
13480 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13481 Py_UCS1 *data = writer->data;
13482
13483 Py_MEMCPY(data + writer->pos, str, len);
13484 break;
13485 }
13486 case PyUnicode_2BYTE_KIND:
13487 {
13488 _PyUnicode_CONVERT_BYTES(
13489 Py_UCS1, Py_UCS2,
13490 ascii, ascii + len,
13491 (Py_UCS2 *)writer->data + writer->pos);
13492 break;
13493 }
13494 case PyUnicode_4BYTE_KIND:
13495 {
13496 _PyUnicode_CONVERT_BYTES(
13497 Py_UCS1, Py_UCS4,
13498 ascii, ascii + len,
13499 (Py_UCS4 *)writer->data + writer->pos);
13500 break;
13501 }
13502 default:
13503 assert(0);
13504 }
13505
13506 writer->pos += len;
13507 return 0;
13508}
13509
13510int
13511_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13512 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013513{
13514 Py_UCS4 maxchar;
13515
13516 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13517 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13518 return -1;
13519 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13520 writer->pos += len;
13521 return 0;
13522}
13523
Victor Stinnerd3f08822012-05-29 12:57:52 +020013524PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013525_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013526{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013527 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013528 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013529 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013530 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013531 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013532 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013533 str = writer->buffer;
13534 writer->buffer = NULL;
13535 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13536 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013537 }
13538 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13539 PyObject *newbuffer;
13540 newbuffer = resize_compact(writer->buffer, writer->pos);
13541 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013542 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013543 return NULL;
13544 }
13545 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013546 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013547 str = writer->buffer;
13548 writer->buffer = NULL;
13549 assert(_PyUnicode_CheckConsistency(str, 1));
13550 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013551}
13552
Victor Stinnerd3f08822012-05-29 12:57:52 +020013553void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013554_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013555{
13556 Py_CLEAR(writer->buffer);
13557}
13558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013560
13561PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013563\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013564Return a formatted version of S, using substitutions from args and kwargs.\n\
13565The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013566
Eric Smith27bbca62010-11-04 17:06:58 +000013567PyDoc_STRVAR(format_map__doc__,
13568 "S.format_map(mapping) -> str\n\
13569\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013570Return a formatted version of S, using substitutions from mapping.\n\
13571The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013572
Eric Smith4a7d76d2008-05-30 18:10:19 +000013573static PyObject *
13574unicode__format__(PyObject* self, PyObject* args)
13575{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013576 PyObject *format_spec;
13577 _PyUnicodeWriter writer;
13578 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013579
13580 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13581 return NULL;
13582
Victor Stinnerd3f08822012-05-29 12:57:52 +020013583 if (PyUnicode_READY(self) == -1)
13584 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013585 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013586 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13587 self, format_spec, 0,
13588 PyUnicode_GET_LENGTH(format_spec));
13589 if (ret == -1) {
13590 _PyUnicodeWriter_Dealloc(&writer);
13591 return NULL;
13592 }
13593 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013594}
13595
Eric Smith8c663262007-08-25 02:26:07 +000013596PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013598\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013599Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013600
13601static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013602unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013604 Py_ssize_t size;
13605
13606 /* If it's a compact object, account for base structure +
13607 character data. */
13608 if (PyUnicode_IS_COMPACT_ASCII(v))
13609 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13610 else if (PyUnicode_IS_COMPACT(v))
13611 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013612 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 else {
13614 /* If it is a two-block object, account for base object, and
13615 for character block if present. */
13616 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013617 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013619 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 }
13621 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013622 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013623 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013625 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013626 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013627
13628 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013629}
13630
13631PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013633
13634static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013635unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013636{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013637 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 if (!copy)
13639 return NULL;
13640 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013641}
13642
Guido van Rossumd57fd912000-03-10 22:53:23 +000013643static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013644 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013645 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013646 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13647 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013648 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13649 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013650 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013651 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13652 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13653 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013654 {"expandtabs", (PyCFunction) unicode_expandtabs,
13655 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013656 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013657 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013658 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13659 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13660 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013661 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013662 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13663 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13664 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013665 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013666 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013667 {"splitlines", (PyCFunction) unicode_splitlines,
13668 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013669 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013670 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13671 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13672 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13673 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13674 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13675 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13676 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13677 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13678 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13679 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13680 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13681 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13682 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13683 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013684 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013685 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013686 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013687 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013688 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013689 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013690 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013691 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013692#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013693 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013694 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013695#endif
13696
Benjamin Peterson14339b62009-01-31 16:36:08 +000013697 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013698 {NULL, NULL}
13699};
13700
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013701static PyObject *
13702unicode_mod(PyObject *v, PyObject *w)
13703{
Brian Curtindfc80e32011-08-10 20:28:54 -050013704 if (!PyUnicode_Check(v))
13705 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013706 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013707}
13708
13709static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 0, /*nb_add*/
13711 0, /*nb_subtract*/
13712 0, /*nb_multiply*/
13713 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013714};
13715
Guido van Rossumd57fd912000-03-10 22:53:23 +000013716static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013717 (lenfunc) unicode_length, /* sq_length */
13718 PyUnicode_Concat, /* sq_concat */
13719 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13720 (ssizeargfunc) unicode_getitem, /* sq_item */
13721 0, /* sq_slice */
13722 0, /* sq_ass_item */
13723 0, /* sq_ass_slice */
13724 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013725};
13726
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013727static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013728unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013729{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013730 if (PyUnicode_READY(self) == -1)
13731 return NULL;
13732
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013733 if (PyIndex_Check(item)) {
13734 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013735 if (i == -1 && PyErr_Occurred())
13736 return NULL;
13737 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013739 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013740 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013741 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013742 PyObject *result;
13743 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013744 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013745 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013747 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013748 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013749 return NULL;
13750 }
13751
13752 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013753 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013754 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013755 slicelength == PyUnicode_GET_LENGTH(self)) {
13756 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013757 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013758 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013759 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013760 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013761 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013762 src_kind = PyUnicode_KIND(self);
13763 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013764 if (!PyUnicode_IS_ASCII(self)) {
13765 kind_limit = kind_maxchar_limit(src_kind);
13766 max_char = 0;
13767 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13768 ch = PyUnicode_READ(src_kind, src_data, cur);
13769 if (ch > max_char) {
13770 max_char = ch;
13771 if (max_char >= kind_limit)
13772 break;
13773 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013774 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013775 }
Victor Stinner55c99112011-10-13 01:17:06 +020013776 else
13777 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013778 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013779 if (result == NULL)
13780 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013781 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013782 dest_data = PyUnicode_DATA(result);
13783
13784 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013785 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13786 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013787 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013788 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013789 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013790 } else {
13791 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13792 return NULL;
13793 }
13794}
13795
13796static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013797 (lenfunc)unicode_length, /* mp_length */
13798 (binaryfunc)unicode_subscript, /* mp_subscript */
13799 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013800};
13801
Guido van Rossumd57fd912000-03-10 22:53:23 +000013802
Guido van Rossumd57fd912000-03-10 22:53:23 +000013803/* Helpers for PyUnicode_Format() */
13804
Victor Stinnera47082312012-10-04 02:19:54 +020013805struct unicode_formatter_t {
13806 PyObject *args;
13807 int args_owned;
13808 Py_ssize_t arglen, argidx;
13809 PyObject *dict;
13810
13811 enum PyUnicode_Kind fmtkind;
13812 Py_ssize_t fmtcnt, fmtpos;
13813 void *fmtdata;
13814 PyObject *fmtstr;
13815
13816 _PyUnicodeWriter writer;
13817};
13818
13819struct unicode_format_arg_t {
13820 Py_UCS4 ch;
13821 int flags;
13822 Py_ssize_t width;
13823 int prec;
13824 int sign;
13825};
13826
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013828unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013829{
Victor Stinnera47082312012-10-04 02:19:54 +020013830 Py_ssize_t argidx = ctx->argidx;
13831
13832 if (argidx < ctx->arglen) {
13833 ctx->argidx++;
13834 if (ctx->arglen < 0)
13835 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 else
Victor Stinnera47082312012-10-04 02:19:54 +020013837 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838 }
13839 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013840 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013841 return NULL;
13842}
13843
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013844/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013845
Victor Stinnera47082312012-10-04 02:19:54 +020013846/* Format a float into the writer if the writer is not NULL, or into *p_output
13847 otherwise.
13848
13849 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850static int
Victor Stinnera47082312012-10-04 02:19:54 +020013851formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13852 PyObject **p_output,
13853 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013855 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013856 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013857 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013858 int prec;
13859 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013860
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861 x = PyFloat_AsDouble(v);
13862 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013863 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013864
Victor Stinnera47082312012-10-04 02:19:54 +020013865 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013868
Victor Stinnera47082312012-10-04 02:19:54 +020013869 if (arg->flags & F_ALT)
13870 dtoa_flags = Py_DTSF_ALT;
13871 else
13872 dtoa_flags = 0;
13873 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013874 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013875 return -1;
13876 len = strlen(p);
13877 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013878 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013879 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013880 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013881 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013882 }
13883 else
13884 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013885 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013886 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013887}
13888
Victor Stinnerd0880d52012-04-27 23:40:13 +020013889/* formatlong() emulates the format codes d, u, o, x and X, and
13890 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13891 * Python's regular ints.
13892 * Return value: a new PyUnicodeObject*, or NULL if error.
13893 * The output string is of the form
13894 * "-"? ("0x" | "0X")? digit+
13895 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13896 * set in flags. The case of hex digits will be correct,
13897 * There will be at least prec digits, zero-filled on the left if
13898 * necessary to get that many.
13899 * val object to be converted
13900 * flags bitmask of format flags; only F_ALT is looked at
13901 * prec minimum number of digits; 0-fill on left if needed
13902 * type a character in [duoxX]; u acts the same as d
13903 *
13904 * CAUTION: o, x and X conversions on regular ints can never
13905 * produce a '-' sign, but can for Python's unbounded ints.
13906 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013907static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013908formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013909{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013910 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013911 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013912 Py_ssize_t i;
13913 int sign; /* 1 if '-', else 0 */
13914 int len; /* number of characters */
13915 Py_ssize_t llen;
13916 int numdigits; /* len == numnondigits + numdigits */
13917 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013918 int prec = arg->prec;
13919 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013920
Victor Stinnerd0880d52012-04-27 23:40:13 +020013921 /* Avoid exceeding SSIZE_T_MAX */
13922 if (prec > INT_MAX-3) {
13923 PyErr_SetString(PyExc_OverflowError,
13924 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013925 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013926 }
13927
13928 assert(PyLong_Check(val));
13929
13930 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013931 default:
13932 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013933 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013934 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013935 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013936 /* int and int subclasses should print numerically when a numeric */
13937 /* format code is used (see issue18780) */
13938 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013939 break;
13940 case 'o':
13941 numnondigits = 2;
13942 result = PyNumber_ToBase(val, 8);
13943 break;
13944 case 'x':
13945 case 'X':
13946 numnondigits = 2;
13947 result = PyNumber_ToBase(val, 16);
13948 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013949 }
13950 if (!result)
13951 return NULL;
13952
13953 assert(unicode_modifiable(result));
13954 assert(PyUnicode_IS_READY(result));
13955 assert(PyUnicode_IS_ASCII(result));
13956
13957 /* To modify the string in-place, there can only be one reference. */
13958 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013959 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013960 PyErr_BadInternalCall();
13961 return NULL;
13962 }
13963 buf = PyUnicode_DATA(result);
13964 llen = PyUnicode_GET_LENGTH(result);
13965 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013966 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013967 PyErr_SetString(PyExc_ValueError,
13968 "string too large in _PyBytes_FormatLong");
13969 return NULL;
13970 }
13971 len = (int)llen;
13972 sign = buf[0] == '-';
13973 numnondigits += sign;
13974 numdigits = len - numnondigits;
13975 assert(numdigits > 0);
13976
13977 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013978 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013979 (type == 'o' || type == 'x' || type == 'X'))) {
13980 assert(buf[sign] == '0');
13981 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13982 buf[sign+1] == 'o');
13983 numnondigits -= 2;
13984 buf += 2;
13985 len -= 2;
13986 if (sign)
13987 buf[0] = '-';
13988 assert(len == numnondigits + numdigits);
13989 assert(numdigits > 0);
13990 }
13991
13992 /* Fill with leading zeroes to meet minimum width. */
13993 if (prec > numdigits) {
13994 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13995 numnondigits + prec);
13996 char *b1;
13997 if (!r1) {
13998 Py_DECREF(result);
13999 return NULL;
14000 }
14001 b1 = PyBytes_AS_STRING(r1);
14002 for (i = 0; i < numnondigits; ++i)
14003 *b1++ = *buf++;
14004 for (i = 0; i < prec - numdigits; i++)
14005 *b1++ = '0';
14006 for (i = 0; i < numdigits; i++)
14007 *b1++ = *buf++;
14008 *b1 = '\0';
14009 Py_DECREF(result);
14010 result = r1;
14011 buf = PyBytes_AS_STRING(result);
14012 len = numnondigits + prec;
14013 }
14014
14015 /* Fix up case for hex conversions. */
14016 if (type == 'X') {
14017 /* Need to convert all lower case letters to upper case.
14018 and need to convert 0x to 0X (and -0x to -0X). */
14019 for (i = 0; i < len; i++)
14020 if (buf[i] >= 'a' && buf[i] <= 'x')
14021 buf[i] -= 'a'-'A';
14022 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014023 if (!PyUnicode_Check(result)
14024 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014025 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014026 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014027 Py_DECREF(result);
14028 result = unicode;
14029 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014030 else if (len != PyUnicode_GET_LENGTH(result)) {
14031 if (PyUnicode_Resize(&result, len) < 0)
14032 Py_CLEAR(result);
14033 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014035}
14036
Ethan Furmandf3ed242014-01-05 06:50:30 -080014037/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014038 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014039 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014040 * -1 and raise an exception on error */
14041static int
Victor Stinnera47082312012-10-04 02:19:54 +020014042mainformatlong(PyObject *v,
14043 struct unicode_format_arg_t *arg,
14044 PyObject **p_output,
14045 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014046{
14047 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014048 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014049
14050 if (!PyNumber_Check(v))
14051 goto wrongtype;
14052
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014053 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014054 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014055 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014056 if (type == 'o' || type == 'x' || type == 'X') {
14057 iobj = PyNumber_Index(v);
14058 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014059 PyErr_Clear();
14060 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14061 "automatic int conversions have been deprecated",
14062 1)) {
14063 return -1;
14064 }
14065 iobj = PyNumber_Long(v);
14066 if (iobj == NULL ) {
14067 if (PyErr_ExceptionMatches(PyExc_TypeError))
14068 goto wrongtype;
14069 return -1;
14070 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014071 }
14072 }
14073 else {
14074 iobj = PyNumber_Long(v);
14075 if (iobj == NULL ) {
14076 if (PyErr_ExceptionMatches(PyExc_TypeError))
14077 goto wrongtype;
14078 return -1;
14079 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 }
14081 assert(PyLong_Check(iobj));
14082 }
14083 else {
14084 iobj = v;
14085 Py_INCREF(iobj);
14086 }
14087
14088 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014089 && arg->width == -1 && arg->prec == -1
14090 && !(arg->flags & (F_SIGN | F_BLANK))
14091 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014092 {
14093 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014094 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 int base;
14096
Victor Stinnera47082312012-10-04 02:19:54 +020014097 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014098 {
14099 default:
14100 assert(0 && "'type' not in [diuoxX]");
14101 case 'd':
14102 case 'i':
14103 case 'u':
14104 base = 10;
14105 break;
14106 case 'o':
14107 base = 8;
14108 break;
14109 case 'x':
14110 case 'X':
14111 base = 16;
14112 break;
14113 }
14114
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014115 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14116 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014117 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014118 }
14119 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014120 return 1;
14121 }
14122
Victor Stinnera47082312012-10-04 02:19:54 +020014123 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014124 Py_DECREF(iobj);
14125 if (res == NULL)
14126 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014127 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014128 return 0;
14129
14130wrongtype:
14131 PyErr_Format(PyExc_TypeError,
14132 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014133 "not %.200s",
14134 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014135 return -1;
14136}
14137
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014138static Py_UCS4
14139formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014140{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014141 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014142 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014143 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014144 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014145 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014146 goto onError;
14147 }
14148 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014149 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014150 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014151 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014152 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014153 if (!PyLong_Check(v)) {
14154 iobj = PyNumber_Index(v);
14155 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014156 PyErr_Clear();
14157 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14158 "automatic int conversions have been deprecated",
14159 1)) {
14160 return -1;
14161 }
14162 iobj = PyNumber_Long(v);
14163 if (iobj == NULL ) {
14164 if (PyErr_ExceptionMatches(PyExc_TypeError))
14165 goto onError;
14166 return -1;
14167 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014168 }
14169 v = iobj;
14170 Py_DECREF(iobj);
14171 }
14172 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014173 x = PyLong_AsLong(v);
14174 if (x == -1 && PyErr_Occurred())
14175 goto onError;
14176
Victor Stinner8faf8212011-12-08 22:14:11 +010014177 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 PyErr_SetString(PyExc_OverflowError,
14179 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014180 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014181 }
14182
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014183 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014184 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014185
Benjamin Peterson29060642009-01-31 22:14:21 +000014186 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014187 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014188 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014189 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014190}
14191
Victor Stinnera47082312012-10-04 02:19:54 +020014192/* Parse options of an argument: flags, width, precision.
14193 Handle also "%(name)" syntax.
14194
14195 Return 0 if the argument has been formatted into arg->str.
14196 Return 1 if the argument has been written into ctx->writer,
14197 Raise an exception and return -1 on error. */
14198static int
14199unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14200 struct unicode_format_arg_t *arg)
14201{
14202#define FORMAT_READ(ctx) \
14203 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14204
14205 PyObject *v;
14206
Victor Stinnera47082312012-10-04 02:19:54 +020014207 if (arg->ch == '(') {
14208 /* Get argument value from a dictionary. Example: "%(name)s". */
14209 Py_ssize_t keystart;
14210 Py_ssize_t keylen;
14211 PyObject *key;
14212 int pcount = 1;
14213
14214 if (ctx->dict == NULL) {
14215 PyErr_SetString(PyExc_TypeError,
14216 "format requires a mapping");
14217 return -1;
14218 }
14219 ++ctx->fmtpos;
14220 --ctx->fmtcnt;
14221 keystart = ctx->fmtpos;
14222 /* Skip over balanced parentheses */
14223 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14224 arg->ch = FORMAT_READ(ctx);
14225 if (arg->ch == ')')
14226 --pcount;
14227 else if (arg->ch == '(')
14228 ++pcount;
14229 ctx->fmtpos++;
14230 }
14231 keylen = ctx->fmtpos - keystart - 1;
14232 if (ctx->fmtcnt < 0 || pcount > 0) {
14233 PyErr_SetString(PyExc_ValueError,
14234 "incomplete format key");
14235 return -1;
14236 }
14237 key = PyUnicode_Substring(ctx->fmtstr,
14238 keystart, keystart + keylen);
14239 if (key == NULL)
14240 return -1;
14241 if (ctx->args_owned) {
14242 Py_DECREF(ctx->args);
14243 ctx->args_owned = 0;
14244 }
14245 ctx->args = PyObject_GetItem(ctx->dict, key);
14246 Py_DECREF(key);
14247 if (ctx->args == NULL)
14248 return -1;
14249 ctx->args_owned = 1;
14250 ctx->arglen = -1;
14251 ctx->argidx = -2;
14252 }
14253
14254 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014255 while (--ctx->fmtcnt >= 0) {
14256 arg->ch = FORMAT_READ(ctx);
14257 ctx->fmtpos++;
14258 switch (arg->ch) {
14259 case '-': arg->flags |= F_LJUST; continue;
14260 case '+': arg->flags |= F_SIGN; continue;
14261 case ' ': arg->flags |= F_BLANK; continue;
14262 case '#': arg->flags |= F_ALT; continue;
14263 case '0': arg->flags |= F_ZERO; continue;
14264 }
14265 break;
14266 }
14267
14268 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014269 if (arg->ch == '*') {
14270 v = unicode_format_getnextarg(ctx);
14271 if (v == NULL)
14272 return -1;
14273 if (!PyLong_Check(v)) {
14274 PyErr_SetString(PyExc_TypeError,
14275 "* wants int");
14276 return -1;
14277 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014278 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014279 if (arg->width == -1 && PyErr_Occurred())
14280 return -1;
14281 if (arg->width < 0) {
14282 arg->flags |= F_LJUST;
14283 arg->width = -arg->width;
14284 }
14285 if (--ctx->fmtcnt >= 0) {
14286 arg->ch = FORMAT_READ(ctx);
14287 ctx->fmtpos++;
14288 }
14289 }
14290 else if (arg->ch >= '0' && arg->ch <= '9') {
14291 arg->width = arg->ch - '0';
14292 while (--ctx->fmtcnt >= 0) {
14293 arg->ch = FORMAT_READ(ctx);
14294 ctx->fmtpos++;
14295 if (arg->ch < '0' || arg->ch > '9')
14296 break;
14297 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14298 mixing signed and unsigned comparison. Since arg->ch is between
14299 '0' and '9', casting to int is safe. */
14300 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14301 PyErr_SetString(PyExc_ValueError,
14302 "width too big");
14303 return -1;
14304 }
14305 arg->width = arg->width*10 + (arg->ch - '0');
14306 }
14307 }
14308
14309 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014310 if (arg->ch == '.') {
14311 arg->prec = 0;
14312 if (--ctx->fmtcnt >= 0) {
14313 arg->ch = FORMAT_READ(ctx);
14314 ctx->fmtpos++;
14315 }
14316 if (arg->ch == '*') {
14317 v = unicode_format_getnextarg(ctx);
14318 if (v == NULL)
14319 return -1;
14320 if (!PyLong_Check(v)) {
14321 PyErr_SetString(PyExc_TypeError,
14322 "* wants int");
14323 return -1;
14324 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014325 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014326 if (arg->prec == -1 && PyErr_Occurred())
14327 return -1;
14328 if (arg->prec < 0)
14329 arg->prec = 0;
14330 if (--ctx->fmtcnt >= 0) {
14331 arg->ch = FORMAT_READ(ctx);
14332 ctx->fmtpos++;
14333 }
14334 }
14335 else if (arg->ch >= '0' && arg->ch <= '9') {
14336 arg->prec = arg->ch - '0';
14337 while (--ctx->fmtcnt >= 0) {
14338 arg->ch = FORMAT_READ(ctx);
14339 ctx->fmtpos++;
14340 if (arg->ch < '0' || arg->ch > '9')
14341 break;
14342 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14343 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014344 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014345 return -1;
14346 }
14347 arg->prec = arg->prec*10 + (arg->ch - '0');
14348 }
14349 }
14350 }
14351
14352 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14353 if (ctx->fmtcnt >= 0) {
14354 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14355 if (--ctx->fmtcnt >= 0) {
14356 arg->ch = FORMAT_READ(ctx);
14357 ctx->fmtpos++;
14358 }
14359 }
14360 }
14361 if (ctx->fmtcnt < 0) {
14362 PyErr_SetString(PyExc_ValueError,
14363 "incomplete format");
14364 return -1;
14365 }
14366 return 0;
14367
14368#undef FORMAT_READ
14369}
14370
14371/* Format one argument. Supported conversion specifiers:
14372
14373 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014374 - "i", "d", "u": int or float
14375 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014376 - "e", "E", "f", "F", "g", "G": float
14377 - "c": int or str (1 character)
14378
Victor Stinner8dbd4212012-12-04 09:30:24 +010014379 When possible, the output is written directly into the Unicode writer
14380 (ctx->writer). A string is created when padding is required.
14381
Victor Stinnera47082312012-10-04 02:19:54 +020014382 Return 0 if the argument has been formatted into *p_str,
14383 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014384 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014385static int
14386unicode_format_arg_format(struct unicode_formatter_t *ctx,
14387 struct unicode_format_arg_t *arg,
14388 PyObject **p_str)
14389{
14390 PyObject *v;
14391 _PyUnicodeWriter *writer = &ctx->writer;
14392
14393 if (ctx->fmtcnt == 0)
14394 ctx->writer.overallocate = 0;
14395
14396 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014397 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014398 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014399 return 1;
14400 }
14401
14402 v = unicode_format_getnextarg(ctx);
14403 if (v == NULL)
14404 return -1;
14405
Victor Stinnera47082312012-10-04 02:19:54 +020014406
14407 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014408 case 's':
14409 case 'r':
14410 case 'a':
14411 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14412 /* Fast path */
14413 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14414 return -1;
14415 return 1;
14416 }
14417
14418 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14419 *p_str = v;
14420 Py_INCREF(*p_str);
14421 }
14422 else {
14423 if (arg->ch == 's')
14424 *p_str = PyObject_Str(v);
14425 else if (arg->ch == 'r')
14426 *p_str = PyObject_Repr(v);
14427 else
14428 *p_str = PyObject_ASCII(v);
14429 }
14430 break;
14431
14432 case 'i':
14433 case 'd':
14434 case 'u':
14435 case 'o':
14436 case 'x':
14437 case 'X':
14438 {
14439 int ret = mainformatlong(v, arg, p_str, writer);
14440 if (ret != 0)
14441 return ret;
14442 arg->sign = 1;
14443 break;
14444 }
14445
14446 case 'e':
14447 case 'E':
14448 case 'f':
14449 case 'F':
14450 case 'g':
14451 case 'G':
14452 if (arg->width == -1 && arg->prec == -1
14453 && !(arg->flags & (F_SIGN | F_BLANK)))
14454 {
14455 /* Fast path */
14456 if (formatfloat(v, arg, NULL, writer) == -1)
14457 return -1;
14458 return 1;
14459 }
14460
14461 arg->sign = 1;
14462 if (formatfloat(v, arg, p_str, NULL) == -1)
14463 return -1;
14464 break;
14465
14466 case 'c':
14467 {
14468 Py_UCS4 ch = formatchar(v);
14469 if (ch == (Py_UCS4) -1)
14470 return -1;
14471 if (arg->width == -1 && arg->prec == -1) {
14472 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014473 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014474 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014475 return 1;
14476 }
14477 *p_str = PyUnicode_FromOrdinal(ch);
14478 break;
14479 }
14480
14481 default:
14482 PyErr_Format(PyExc_ValueError,
14483 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014484 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014485 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14486 (int)arg->ch,
14487 ctx->fmtpos - 1);
14488 return -1;
14489 }
14490 if (*p_str == NULL)
14491 return -1;
14492 assert (PyUnicode_Check(*p_str));
14493 return 0;
14494}
14495
14496static int
14497unicode_format_arg_output(struct unicode_formatter_t *ctx,
14498 struct unicode_format_arg_t *arg,
14499 PyObject *str)
14500{
14501 Py_ssize_t len;
14502 enum PyUnicode_Kind kind;
14503 void *pbuf;
14504 Py_ssize_t pindex;
14505 Py_UCS4 signchar;
14506 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014507 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014508 Py_ssize_t sublen;
14509 _PyUnicodeWriter *writer = &ctx->writer;
14510 Py_UCS4 fill;
14511
14512 fill = ' ';
14513 if (arg->sign && arg->flags & F_ZERO)
14514 fill = '0';
14515
14516 if (PyUnicode_READY(str) == -1)
14517 return -1;
14518
14519 len = PyUnicode_GET_LENGTH(str);
14520 if ((arg->width == -1 || arg->width <= len)
14521 && (arg->prec == -1 || arg->prec >= len)
14522 && !(arg->flags & (F_SIGN | F_BLANK)))
14523 {
14524 /* Fast path */
14525 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14526 return -1;
14527 return 0;
14528 }
14529
14530 /* Truncate the string for "s", "r" and "a" formats
14531 if the precision is set */
14532 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14533 if (arg->prec >= 0 && len > arg->prec)
14534 len = arg->prec;
14535 }
14536
14537 /* Adjust sign and width */
14538 kind = PyUnicode_KIND(str);
14539 pbuf = PyUnicode_DATA(str);
14540 pindex = 0;
14541 signchar = '\0';
14542 if (arg->sign) {
14543 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14544 if (ch == '-' || ch == '+') {
14545 signchar = ch;
14546 len--;
14547 pindex++;
14548 }
14549 else if (arg->flags & F_SIGN)
14550 signchar = '+';
14551 else if (arg->flags & F_BLANK)
14552 signchar = ' ';
14553 else
14554 arg->sign = 0;
14555 }
14556 if (arg->width < len)
14557 arg->width = len;
14558
14559 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014560 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014561 if (!(arg->flags & F_LJUST)) {
14562 if (arg->sign) {
14563 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014564 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014565 }
14566 else {
14567 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014568 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014569 }
14570 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014571 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14572 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014573 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014574 }
14575
Victor Stinnera47082312012-10-04 02:19:54 +020014576 buflen = arg->width;
14577 if (arg->sign && len == arg->width)
14578 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014579 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014580 return -1;
14581
14582 /* Write the sign if needed */
14583 if (arg->sign) {
14584 if (fill != ' ') {
14585 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14586 writer->pos += 1;
14587 }
14588 if (arg->width > len)
14589 arg->width--;
14590 }
14591
14592 /* Write the numeric prefix for "x", "X" and "o" formats
14593 if the alternate form is used.
14594 For example, write "0x" for the "%#x" format. */
14595 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14596 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14597 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14598 if (fill != ' ') {
14599 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14600 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14601 writer->pos += 2;
14602 pindex += 2;
14603 }
14604 arg->width -= 2;
14605 if (arg->width < 0)
14606 arg->width = 0;
14607 len -= 2;
14608 }
14609
14610 /* Pad left with the fill character if needed */
14611 if (arg->width > len && !(arg->flags & F_LJUST)) {
14612 sublen = arg->width - len;
14613 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14614 writer->pos += sublen;
14615 arg->width = len;
14616 }
14617
14618 /* If padding with spaces: write sign if needed and/or numeric prefix if
14619 the alternate form is used */
14620 if (fill == ' ') {
14621 if (arg->sign) {
14622 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14623 writer->pos += 1;
14624 }
14625 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14626 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14627 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14628 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14629 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14630 writer->pos += 2;
14631 pindex += 2;
14632 }
14633 }
14634
14635 /* Write characters */
14636 if (len) {
14637 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14638 str, pindex, len);
14639 writer->pos += len;
14640 }
14641
14642 /* Pad right with the fill character if needed */
14643 if (arg->width > len) {
14644 sublen = arg->width - len;
14645 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14646 writer->pos += sublen;
14647 }
14648 return 0;
14649}
14650
14651/* Helper of PyUnicode_Format(): format one arg.
14652 Return 0 on success, raise an exception and return -1 on error. */
14653static int
14654unicode_format_arg(struct unicode_formatter_t *ctx)
14655{
14656 struct unicode_format_arg_t arg;
14657 PyObject *str;
14658 int ret;
14659
Victor Stinner8dbd4212012-12-04 09:30:24 +010014660 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14661 arg.flags = 0;
14662 arg.width = -1;
14663 arg.prec = -1;
14664 arg.sign = 0;
14665 str = NULL;
14666
Victor Stinnera47082312012-10-04 02:19:54 +020014667 ret = unicode_format_arg_parse(ctx, &arg);
14668 if (ret == -1)
14669 return -1;
14670
14671 ret = unicode_format_arg_format(ctx, &arg, &str);
14672 if (ret == -1)
14673 return -1;
14674
14675 if (ret != 1) {
14676 ret = unicode_format_arg_output(ctx, &arg, str);
14677 Py_DECREF(str);
14678 if (ret == -1)
14679 return -1;
14680 }
14681
14682 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14683 PyErr_SetString(PyExc_TypeError,
14684 "not all arguments converted during string formatting");
14685 return -1;
14686 }
14687 return 0;
14688}
14689
Alexander Belopolsky40018472011-02-26 01:02:56 +000014690PyObject *
14691PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014692{
Victor Stinnera47082312012-10-04 02:19:54 +020014693 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014694
Guido van Rossumd57fd912000-03-10 22:53:23 +000014695 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014696 PyErr_BadInternalCall();
14697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014698 }
Victor Stinnera47082312012-10-04 02:19:54 +020014699
14700 ctx.fmtstr = PyUnicode_FromObject(format);
14701 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014702 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014703 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14704 Py_DECREF(ctx.fmtstr);
14705 return NULL;
14706 }
14707 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14708 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14709 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14710 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014711
Victor Stinner8f674cc2013-04-17 23:02:17 +020014712 _PyUnicodeWriter_Init(&ctx.writer);
14713 ctx.writer.min_length = ctx.fmtcnt + 100;
14714 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014715
Guido van Rossumd57fd912000-03-10 22:53:23 +000014716 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014717 ctx.arglen = PyTuple_Size(args);
14718 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014719 }
14720 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014721 ctx.arglen = -1;
14722 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014723 }
Victor Stinnera47082312012-10-04 02:19:54 +020014724 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014725 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014726 ctx.dict = args;
14727 else
14728 ctx.dict = NULL;
14729 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014730
Victor Stinnera47082312012-10-04 02:19:54 +020014731 while (--ctx.fmtcnt >= 0) {
14732 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014733 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014734
14735 nonfmtpos = ctx.fmtpos++;
14736 while (ctx.fmtcnt >= 0 &&
14737 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14738 ctx.fmtpos++;
14739 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014740 }
Victor Stinnera47082312012-10-04 02:19:54 +020014741 if (ctx.fmtcnt < 0) {
14742 ctx.fmtpos--;
14743 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014744 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014745
Victor Stinnercfc4c132013-04-03 01:48:39 +020014746 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14747 nonfmtpos, ctx.fmtpos) < 0)
14748 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014749 }
14750 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014751 ctx.fmtpos++;
14752 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014753 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014754 }
14755 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014756
Victor Stinnera47082312012-10-04 02:19:54 +020014757 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014758 PyErr_SetString(PyExc_TypeError,
14759 "not all arguments converted during string formatting");
14760 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014761 }
14762
Victor Stinnera47082312012-10-04 02:19:54 +020014763 if (ctx.args_owned) {
14764 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014765 }
Victor Stinnera47082312012-10-04 02:19:54 +020014766 Py_DECREF(ctx.fmtstr);
14767 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014768
Benjamin Peterson29060642009-01-31 22:14:21 +000014769 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014770 Py_DECREF(ctx.fmtstr);
14771 _PyUnicodeWriter_Dealloc(&ctx.writer);
14772 if (ctx.args_owned) {
14773 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014774 }
14775 return NULL;
14776}
14777
Jeremy Hylton938ace62002-07-17 16:30:39 +000014778static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014779unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14780
Tim Peters6d6c1a32001-08-02 04:15:00 +000014781static PyObject *
14782unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14783{
Benjamin Peterson29060642009-01-31 22:14:21 +000014784 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014785 static char *kwlist[] = {"object", "encoding", "errors", 0};
14786 char *encoding = NULL;
14787 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014788
Benjamin Peterson14339b62009-01-31 16:36:08 +000014789 if (type != &PyUnicode_Type)
14790 return unicode_subtype_new(type, args, kwds);
14791 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014792 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014793 return NULL;
14794 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014795 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014796 if (encoding == NULL && errors == NULL)
14797 return PyObject_Str(x);
14798 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014799 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014800}
14801
Guido van Rossume023fe02001-08-30 03:12:59 +000014802static PyObject *
14803unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14804{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014805 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014806 Py_ssize_t length, char_size;
14807 int share_wstr, share_utf8;
14808 unsigned int kind;
14809 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014810
Benjamin Peterson14339b62009-01-31 16:36:08 +000014811 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014812
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014813 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014814 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014815 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014816 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014817 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014818 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014819 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014820 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014821
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014822 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014823 if (self == NULL) {
14824 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014825 return NULL;
14826 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014827 kind = PyUnicode_KIND(unicode);
14828 length = PyUnicode_GET_LENGTH(unicode);
14829
14830 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014831#ifdef Py_DEBUG
14832 _PyUnicode_HASH(self) = -1;
14833#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014834 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014835#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014836 _PyUnicode_STATE(self).interned = 0;
14837 _PyUnicode_STATE(self).kind = kind;
14838 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014839 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014840 _PyUnicode_STATE(self).ready = 1;
14841 _PyUnicode_WSTR(self) = NULL;
14842 _PyUnicode_UTF8_LENGTH(self) = 0;
14843 _PyUnicode_UTF8(self) = NULL;
14844 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014845 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014846
14847 share_utf8 = 0;
14848 share_wstr = 0;
14849 if (kind == PyUnicode_1BYTE_KIND) {
14850 char_size = 1;
14851 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14852 share_utf8 = 1;
14853 }
14854 else if (kind == PyUnicode_2BYTE_KIND) {
14855 char_size = 2;
14856 if (sizeof(wchar_t) == 2)
14857 share_wstr = 1;
14858 }
14859 else {
14860 assert(kind == PyUnicode_4BYTE_KIND);
14861 char_size = 4;
14862 if (sizeof(wchar_t) == 4)
14863 share_wstr = 1;
14864 }
14865
14866 /* Ensure we won't overflow the length. */
14867 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14868 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014869 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014870 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014871 data = PyObject_MALLOC((length + 1) * char_size);
14872 if (data == NULL) {
14873 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014874 goto onError;
14875 }
14876
Victor Stinnerc3c74152011-10-02 20:39:55 +020014877 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014878 if (share_utf8) {
14879 _PyUnicode_UTF8_LENGTH(self) = length;
14880 _PyUnicode_UTF8(self) = data;
14881 }
14882 if (share_wstr) {
14883 _PyUnicode_WSTR_LENGTH(self) = length;
14884 _PyUnicode_WSTR(self) = (wchar_t *)data;
14885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014886
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014887 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014888 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014889 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014890#ifdef Py_DEBUG
14891 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14892#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014893 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014894 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014895
14896onError:
14897 Py_DECREF(unicode);
14898 Py_DECREF(self);
14899 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014900}
14901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014902PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014903"str(object='') -> str\n\
14904str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014905\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014906Create a new string object from the given object. If encoding or\n\
14907errors is specified, then the object must expose a data buffer\n\
14908that will be decoded using the given encoding and error handler.\n\
14909Otherwise, returns the result of object.__str__() (if defined)\n\
14910or repr(object).\n\
14911encoding defaults to sys.getdefaultencoding().\n\
14912errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014913
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014914static PyObject *unicode_iter(PyObject *seq);
14915
Guido van Rossumd57fd912000-03-10 22:53:23 +000014916PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014917 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014918 "str", /* tp_name */
14919 sizeof(PyUnicodeObject), /* tp_size */
14920 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014921 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014922 (destructor)unicode_dealloc, /* tp_dealloc */
14923 0, /* tp_print */
14924 0, /* tp_getattr */
14925 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014926 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014927 unicode_repr, /* tp_repr */
14928 &unicode_as_number, /* tp_as_number */
14929 &unicode_as_sequence, /* tp_as_sequence */
14930 &unicode_as_mapping, /* tp_as_mapping */
14931 (hashfunc) unicode_hash, /* tp_hash*/
14932 0, /* tp_call*/
14933 (reprfunc) unicode_str, /* tp_str */
14934 PyObject_GenericGetAttr, /* tp_getattro */
14935 0, /* tp_setattro */
14936 0, /* tp_as_buffer */
14937 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014938 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014939 unicode_doc, /* tp_doc */
14940 0, /* tp_traverse */
14941 0, /* tp_clear */
14942 PyUnicode_RichCompare, /* tp_richcompare */
14943 0, /* tp_weaklistoffset */
14944 unicode_iter, /* tp_iter */
14945 0, /* tp_iternext */
14946 unicode_methods, /* tp_methods */
14947 0, /* tp_members */
14948 0, /* tp_getset */
14949 &PyBaseObject_Type, /* tp_base */
14950 0, /* tp_dict */
14951 0, /* tp_descr_get */
14952 0, /* tp_descr_set */
14953 0, /* tp_dictoffset */
14954 0, /* tp_init */
14955 0, /* tp_alloc */
14956 unicode_new, /* tp_new */
14957 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014958};
14959
14960/* Initialize the Unicode implementation */
14961
Victor Stinner3a50e702011-10-18 21:21:00 +020014962int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014963{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014964 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014965 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014966 0x000A, /* LINE FEED */
14967 0x000D, /* CARRIAGE RETURN */
14968 0x001C, /* FILE SEPARATOR */
14969 0x001D, /* GROUP SEPARATOR */
14970 0x001E, /* RECORD SEPARATOR */
14971 0x0085, /* NEXT LINE */
14972 0x2028, /* LINE SEPARATOR */
14973 0x2029, /* PARAGRAPH SEPARATOR */
14974 };
14975
Fred Drakee4315f52000-05-09 19:53:39 +000014976 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014977 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014978 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014979 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014980 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014981
Guido van Rossumcacfc072002-05-24 19:01:59 +000014982 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014983 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014984
14985 /* initialize the linebreak bloom filter */
14986 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014987 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014988 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014989
Christian Heimes26532f72013-07-20 14:57:16 +020014990 if (PyType_Ready(&EncodingMapType) < 0)
14991 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014992
Benjamin Petersonc4311282012-10-30 23:21:10 -040014993 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14994 Py_FatalError("Can't initialize field name iterator type");
14995
14996 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14997 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014998
Victor Stinner3a50e702011-10-18 21:21:00 +020014999#ifdef HAVE_MBCS
15000 winver.dwOSVersionInfoSize = sizeof(winver);
15001 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
15002 PyErr_SetFromWindowsErr(0);
15003 return -1;
15004 }
15005#endif
15006 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007}
15008
15009/* Finalize the Unicode implementation */
15010
Christian Heimesa156e092008-02-16 07:38:31 +000015011int
15012PyUnicode_ClearFreeList(void)
15013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015014 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015015}
15016
Guido van Rossumd57fd912000-03-10 22:53:23 +000015017void
Thomas Wouters78890102000-07-22 19:25:51 +000015018_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015019{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015020 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021
Serhiy Storchaka05997252013-01-26 12:14:02 +020015022 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015023
Serhiy Storchaka05997252013-01-26 12:14:02 +020015024 for (i = 0; i < 256; i++)
15025 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015026 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015027 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015028}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015029
Walter Dörwald16807132007-05-25 13:52:07 +000015030void
15031PyUnicode_InternInPlace(PyObject **p)
15032{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015033 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015035#ifdef Py_DEBUG
15036 assert(s != NULL);
15037 assert(_PyUnicode_CHECK(s));
15038#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015039 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015040 return;
15041#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015042 /* If it's a subclass, we don't really know what putting
15043 it in the interned dict might do. */
15044 if (!PyUnicode_CheckExact(s))
15045 return;
15046 if (PyUnicode_CHECK_INTERNED(s))
15047 return;
15048 if (interned == NULL) {
15049 interned = PyDict_New();
15050 if (interned == NULL) {
15051 PyErr_Clear(); /* Don't leave an exception */
15052 return;
15053 }
15054 }
15055 /* It might be that the GetItem call fails even
15056 though the key is present in the dictionary,
15057 namely when this happens during a stack overflow. */
15058 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015059 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015060 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015061
Victor Stinnerf0335102013-04-14 19:13:03 +020015062 if (t) {
15063 Py_INCREF(t);
15064 Py_DECREF(*p);
15065 *p = t;
15066 return;
15067 }
Walter Dörwald16807132007-05-25 13:52:07 +000015068
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015070 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 PyErr_Clear();
15072 PyThreadState_GET()->recursion_critical = 0;
15073 return;
15074 }
15075 PyThreadState_GET()->recursion_critical = 0;
15076 /* The two references in interned are not counted by refcnt.
15077 The deallocator will take care of this */
15078 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015079 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015080}
15081
15082void
15083PyUnicode_InternImmortal(PyObject **p)
15084{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015085 PyUnicode_InternInPlace(p);
15086 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015087 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015088 Py_INCREF(*p);
15089 }
Walter Dörwald16807132007-05-25 13:52:07 +000015090}
15091
15092PyObject *
15093PyUnicode_InternFromString(const char *cp)
15094{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015095 PyObject *s = PyUnicode_FromString(cp);
15096 if (s == NULL)
15097 return NULL;
15098 PyUnicode_InternInPlace(&s);
15099 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015100}
15101
Alexander Belopolsky40018472011-02-26 01:02:56 +000015102void
15103_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015104{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015105 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015106 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 Py_ssize_t i, n;
15108 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015109
Benjamin Peterson14339b62009-01-31 16:36:08 +000015110 if (interned == NULL || !PyDict_Check(interned))
15111 return;
15112 keys = PyDict_Keys(interned);
15113 if (keys == NULL || !PyList_Check(keys)) {
15114 PyErr_Clear();
15115 return;
15116 }
Walter Dörwald16807132007-05-25 13:52:07 +000015117
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15119 detector, interned unicode strings are not forcibly deallocated;
15120 rather, we give them their stolen references back, and then clear
15121 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015122
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 n = PyList_GET_SIZE(keys);
15124 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015125 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015127 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015128 if (PyUnicode_READY(s) == -1) {
15129 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015130 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015131 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015133 case SSTATE_NOT_INTERNED:
15134 /* XXX Shouldn't happen */
15135 break;
15136 case SSTATE_INTERNED_IMMORTAL:
15137 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015138 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 break;
15140 case SSTATE_INTERNED_MORTAL:
15141 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015142 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 break;
15144 default:
15145 Py_FatalError("Inconsistent interned string state.");
15146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015147 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 }
15149 fprintf(stderr, "total size of all interned strings: "
15150 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15151 "mortal/immortal\n", mortal_size, immortal_size);
15152 Py_DECREF(keys);
15153 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015154 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015155}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015156
15157
15158/********************* Unicode Iterator **************************/
15159
15160typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015161 PyObject_HEAD
15162 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015163 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015164} unicodeiterobject;
15165
15166static void
15167unicodeiter_dealloc(unicodeiterobject *it)
15168{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015169 _PyObject_GC_UNTRACK(it);
15170 Py_XDECREF(it->it_seq);
15171 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015172}
15173
15174static int
15175unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15176{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015177 Py_VISIT(it->it_seq);
15178 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015179}
15180
15181static PyObject *
15182unicodeiter_next(unicodeiterobject *it)
15183{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015184 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015185
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 assert(it != NULL);
15187 seq = it->it_seq;
15188 if (seq == NULL)
15189 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015190 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015192 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15193 int kind = PyUnicode_KIND(seq);
15194 void *data = PyUnicode_DATA(seq);
15195 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15196 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015197 if (item != NULL)
15198 ++it->it_index;
15199 return item;
15200 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015201
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 Py_DECREF(seq);
15203 it->it_seq = NULL;
15204 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015205}
15206
15207static PyObject *
15208unicodeiter_len(unicodeiterobject *it)
15209{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 Py_ssize_t len = 0;
15211 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015212 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015213 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015214}
15215
15216PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15217
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015218static PyObject *
15219unicodeiter_reduce(unicodeiterobject *it)
15220{
15221 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015222 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015223 it->it_seq, it->it_index);
15224 } else {
15225 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15226 if (u == NULL)
15227 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015228 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015229 }
15230}
15231
15232PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15233
15234static PyObject *
15235unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15236{
15237 Py_ssize_t index = PyLong_AsSsize_t(state);
15238 if (index == -1 && PyErr_Occurred())
15239 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015240 if (it->it_seq != NULL) {
15241 if (index < 0)
15242 index = 0;
15243 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15244 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15245 it->it_index = index;
15246 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015247 Py_RETURN_NONE;
15248}
15249
15250PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15251
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015252static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015254 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015255 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15256 reduce_doc},
15257 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15258 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015260};
15261
15262PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15264 "str_iterator", /* tp_name */
15265 sizeof(unicodeiterobject), /* tp_basicsize */
15266 0, /* tp_itemsize */
15267 /* methods */
15268 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15269 0, /* tp_print */
15270 0, /* tp_getattr */
15271 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015272 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 0, /* tp_repr */
15274 0, /* tp_as_number */
15275 0, /* tp_as_sequence */
15276 0, /* tp_as_mapping */
15277 0, /* tp_hash */
15278 0, /* tp_call */
15279 0, /* tp_str */
15280 PyObject_GenericGetAttr, /* tp_getattro */
15281 0, /* tp_setattro */
15282 0, /* tp_as_buffer */
15283 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15284 0, /* tp_doc */
15285 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15286 0, /* tp_clear */
15287 0, /* tp_richcompare */
15288 0, /* tp_weaklistoffset */
15289 PyObject_SelfIter, /* tp_iter */
15290 (iternextfunc)unicodeiter_next, /* tp_iternext */
15291 unicodeiter_methods, /* tp_methods */
15292 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015293};
15294
15295static PyObject *
15296unicode_iter(PyObject *seq)
15297{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015299
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 if (!PyUnicode_Check(seq)) {
15301 PyErr_BadInternalCall();
15302 return NULL;
15303 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015304 if (PyUnicode_READY(seq) == -1)
15305 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015306 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15307 if (it == NULL)
15308 return NULL;
15309 it->it_index = 0;
15310 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015311 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 _PyObject_GC_TRACK(it);
15313 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015314}
15315
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015316
15317size_t
15318Py_UNICODE_strlen(const Py_UNICODE *u)
15319{
15320 int res = 0;
15321 while(*u++)
15322 res++;
15323 return res;
15324}
15325
15326Py_UNICODE*
15327Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15328{
15329 Py_UNICODE *u = s1;
15330 while ((*u++ = *s2++));
15331 return s1;
15332}
15333
15334Py_UNICODE*
15335Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15336{
15337 Py_UNICODE *u = s1;
15338 while ((*u++ = *s2++))
15339 if (n-- == 0)
15340 break;
15341 return s1;
15342}
15343
15344Py_UNICODE*
15345Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15346{
15347 Py_UNICODE *u1 = s1;
15348 u1 += Py_UNICODE_strlen(u1);
15349 Py_UNICODE_strcpy(u1, s2);
15350 return s1;
15351}
15352
15353int
15354Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15355{
15356 while (*s1 && *s2 && *s1 == *s2)
15357 s1++, s2++;
15358 if (*s1 && *s2)
15359 return (*s1 < *s2) ? -1 : +1;
15360 if (*s1)
15361 return 1;
15362 if (*s2)
15363 return -1;
15364 return 0;
15365}
15366
15367int
15368Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15369{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015370 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015371 for (; n != 0; n--) {
15372 u1 = *s1;
15373 u2 = *s2;
15374 if (u1 != u2)
15375 return (u1 < u2) ? -1 : +1;
15376 if (u1 == '\0')
15377 return 0;
15378 s1++;
15379 s2++;
15380 }
15381 return 0;
15382}
15383
15384Py_UNICODE*
15385Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15386{
15387 const Py_UNICODE *p;
15388 for (p = s; *p; p++)
15389 if (*p == c)
15390 return (Py_UNICODE*)p;
15391 return NULL;
15392}
15393
15394Py_UNICODE*
15395Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15396{
15397 const Py_UNICODE *p;
15398 p = s + Py_UNICODE_strlen(s);
15399 while (p != s) {
15400 p--;
15401 if (*p == c)
15402 return (Py_UNICODE*)p;
15403 }
15404 return NULL;
15405}
Victor Stinner331ea922010-08-10 16:37:20 +000015406
Victor Stinner71133ff2010-09-01 23:43:53 +000015407Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015408PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015409{
Victor Stinner577db2c2011-10-11 22:12:48 +020015410 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015411 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015413 if (!PyUnicode_Check(unicode)) {
15414 PyErr_BadArgument();
15415 return NULL;
15416 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015417 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015418 if (u == NULL)
15419 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015420 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015421 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015422 PyErr_NoMemory();
15423 return NULL;
15424 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015425 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015426 size *= sizeof(Py_UNICODE);
15427 copy = PyMem_Malloc(size);
15428 if (copy == NULL) {
15429 PyErr_NoMemory();
15430 return NULL;
15431 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015432 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015433 return copy;
15434}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015435
Georg Brandl66c221e2010-10-14 07:04:07 +000015436/* A _string module, to export formatter_parser and formatter_field_name_split
15437 to the string.Formatter class implemented in Python. */
15438
15439static PyMethodDef _string_methods[] = {
15440 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15441 METH_O, PyDoc_STR("split the argument as a field name")},
15442 {"formatter_parser", (PyCFunction) formatter_parser,
15443 METH_O, PyDoc_STR("parse the argument as a format string")},
15444 {NULL, NULL}
15445};
15446
15447static struct PyModuleDef _string_module = {
15448 PyModuleDef_HEAD_INIT,
15449 "_string",
15450 PyDoc_STR("string helper module"),
15451 0,
15452 _string_methods,
15453 NULL,
15454 NULL,
15455 NULL,
15456 NULL
15457};
15458
15459PyMODINIT_FUNC
15460PyInit__string(void)
15461{
15462 return PyModule_Create(&_string_module);
15463}
15464
15465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015466#ifdef __cplusplus
15467}
15468#endif