blob: 6fc3683efcdc95a267939b731e6d5819ba33890d [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;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001538 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1539 PyErr_NoMemory();
1540 return -1;
1541 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001542 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1543 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001544 PyErr_NoMemory();
1545 return -1;
1546 }
1547 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1548 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001549 _PyUnicode_UTF8(unicode) = NULL;
1550 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001551 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1552 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001553 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001554 PyObject_FREE(_PyUnicode_WSTR(unicode));
1555 _PyUnicode_WSTR(unicode) = NULL;
1556 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1557#else
1558 assert(num_surrogates == 0);
1559
Victor Stinnerc3c74152011-10-02 20:39:55 +02001560 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001562 _PyUnicode_UTF8(unicode) = NULL;
1563 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1565#endif
1566 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1567 }
1568 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001569 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001570 return 0;
1571}
1572
Alexander Belopolsky40018472011-02-26 01:02:56 +00001573static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001574unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001575{
Walter Dörwald16807132007-05-25 13:52:07 +00001576 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001577 case SSTATE_NOT_INTERNED:
1578 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001579
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 case SSTATE_INTERNED_MORTAL:
1581 /* revive dead object temporarily for DelItem */
1582 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001583 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 Py_FatalError(
1585 "deletion of interned string failed");
1586 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001587
Benjamin Peterson29060642009-01-31 22:14:21 +00001588 case SSTATE_INTERNED_IMMORTAL:
1589 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001590
Benjamin Peterson29060642009-01-31 22:14:21 +00001591 default:
1592 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001593 }
1594
Victor Stinner03490912011-10-03 23:45:12 +02001595 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001596 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001597 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001598 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001599 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1600 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001602 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001603}
1604
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001605#ifdef Py_DEBUG
1606static int
1607unicode_is_singleton(PyObject *unicode)
1608{
1609 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1610 if (unicode == unicode_empty)
1611 return 1;
1612 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1613 {
1614 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1615 if (ch < 256 && unicode_latin1[ch] == unicode)
1616 return 1;
1617 }
1618 return 0;
1619}
1620#endif
1621
Alexander Belopolsky40018472011-02-26 01:02:56 +00001622static int
Victor Stinner488fa492011-12-12 00:01:39 +01001623unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001624{
Victor Stinner488fa492011-12-12 00:01:39 +01001625 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (Py_REFCNT(unicode) != 1)
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (_PyUnicode_HASH(unicode) != -1)
1629 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001630 if (PyUnicode_CHECK_INTERNED(unicode))
1631 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001632 if (!PyUnicode_CheckExact(unicode))
1633 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001634#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001635 /* singleton refcount is greater than 1 */
1636 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001637#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001638 return 1;
1639}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001640
Victor Stinnerfe226c02011-10-03 03:52:20 +02001641static int
1642unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1643{
1644 PyObject *unicode;
1645 Py_ssize_t old_length;
1646
1647 assert(p_unicode != NULL);
1648 unicode = *p_unicode;
1649
1650 assert(unicode != NULL);
1651 assert(PyUnicode_Check(unicode));
1652 assert(0 <= length);
1653
Victor Stinner910337b2011-10-03 03:20:16 +02001654 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001655 old_length = PyUnicode_WSTR_LENGTH(unicode);
1656 else
1657 old_length = PyUnicode_GET_LENGTH(unicode);
1658 if (old_length == length)
1659 return 0;
1660
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001662 _Py_INCREF_UNICODE_EMPTY();
1663 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001664 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001665 Py_DECREF(*p_unicode);
1666 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001667 return 0;
1668 }
1669
Victor Stinner488fa492011-12-12 00:01:39 +01001670 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001671 PyObject *copy = resize_copy(unicode, length);
1672 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001673 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001674 Py_DECREF(*p_unicode);
1675 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001676 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001677 }
1678
Victor Stinnerfe226c02011-10-03 03:52:20 +02001679 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001680 PyObject *new_unicode = resize_compact(unicode, length);
1681 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001682 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001683 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001684 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001685 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001686 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001687}
1688
Alexander Belopolsky40018472011-02-26 01:02:56 +00001689int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001690PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001691{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001692 PyObject *unicode;
1693 if (p_unicode == NULL) {
1694 PyErr_BadInternalCall();
1695 return -1;
1696 }
1697 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001698 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001699 {
1700 PyErr_BadInternalCall();
1701 return -1;
1702 }
1703 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001704}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001705
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001706/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001707
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001708 WARNING: The function doesn't copy the terminating null character and
1709 doesn't check the maximum character (may write a latin1 character in an
1710 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001711static void
1712unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1713 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001714{
1715 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1716 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001717 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001718
1719 switch (kind) {
1720 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001721 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001722#ifdef Py_DEBUG
1723 if (PyUnicode_IS_ASCII(unicode)) {
1724 Py_UCS4 maxchar = ucs1lib_find_max_char(
1725 (const Py_UCS1*)str,
1726 (const Py_UCS1*)str + len);
1727 assert(maxchar < 128);
1728 }
1729#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001730 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001731 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001732 }
1733 case PyUnicode_2BYTE_KIND: {
1734 Py_UCS2 *start = (Py_UCS2 *)data + index;
1735 Py_UCS2 *ucs2 = start;
1736 assert(index <= PyUnicode_GET_LENGTH(unicode));
1737
Victor Stinner184252a2012-06-16 02:57:41 +02001738 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 *ucs2 = (Py_UCS2)*str;
1740
1741 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001742 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001743 }
1744 default: {
1745 Py_UCS4 *start = (Py_UCS4 *)data + index;
1746 Py_UCS4 *ucs4 = start;
1747 assert(kind == PyUnicode_4BYTE_KIND);
1748 assert(index <= PyUnicode_GET_LENGTH(unicode));
1749
Victor Stinner184252a2012-06-16 02:57:41 +02001750 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001751 *ucs4 = (Py_UCS4)*str;
1752
1753 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001754 }
1755 }
1756}
1757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758static PyObject*
1759get_latin1_char(unsigned char ch)
1760{
Victor Stinnera464fc12011-10-02 20:39:30 +02001761 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001763 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 if (!unicode)
1765 return NULL;
1766 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001767 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768 unicode_latin1[ch] = unicode;
1769 }
1770 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001771 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772}
1773
Victor Stinner985a82a2014-01-03 12:53:47 +01001774static PyObject*
1775unicode_char(Py_UCS4 ch)
1776{
1777 PyObject *unicode;
1778
1779 assert(ch <= MAX_UNICODE);
1780
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001781 if (ch < 256)
1782 return get_latin1_char(ch);
1783
Victor Stinner985a82a2014-01-03 12:53:47 +01001784 unicode = PyUnicode_New(1, ch);
1785 if (unicode == NULL)
1786 return NULL;
1787 switch (PyUnicode_KIND(unicode)) {
1788 case PyUnicode_1BYTE_KIND:
1789 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1790 break;
1791 case PyUnicode_2BYTE_KIND:
1792 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1793 break;
1794 default:
1795 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1796 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1797 }
1798 assert(_PyUnicode_CheckConsistency(unicode, 1));
1799 return unicode;
1800}
1801
Alexander Belopolsky40018472011-02-26 01:02:56 +00001802PyObject *
1803PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001804{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001805 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 Py_UCS4 maxchar = 0;
1807 Py_ssize_t num_surrogates;
1808
1809 if (u == NULL)
1810 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001811
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001812 /* If the Unicode data is known at construction time, we can apply
1813 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001816 if (size == 0)
1817 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819 /* Single character Unicode objects in the Latin-1 range are
1820 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001821 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001822 return get_latin1_char((unsigned char)*u);
1823
1824 /* If not empty and not single character, copy the Unicode data
1825 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001826 if (find_maxchar_surrogates(u, u + size,
1827 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 return NULL;
1829
Victor Stinner8faf8212011-12-08 22:14:11 +01001830 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001831 if (!unicode)
1832 return NULL;
1833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001834 switch (PyUnicode_KIND(unicode)) {
1835 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001836 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1838 break;
1839 case PyUnicode_2BYTE_KIND:
1840#if Py_UNICODE_SIZE == 2
1841 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1842#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001843 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001844 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1845#endif
1846 break;
1847 case PyUnicode_4BYTE_KIND:
1848#if SIZEOF_WCHAR_T == 2
1849 /* This is the only case which has to process surrogates, thus
1850 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001851 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001852#else
1853 assert(num_surrogates == 0);
1854 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1855#endif
1856 break;
1857 default:
1858 assert(0 && "Impossible state");
1859 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001860
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001862}
1863
Alexander Belopolsky40018472011-02-26 01:02:56 +00001864PyObject *
1865PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001866{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001867 if (size < 0) {
1868 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001869 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001870 return NULL;
1871 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001872 if (u != NULL)
1873 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1874 else
1875 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001876}
1877
Alexander Belopolsky40018472011-02-26 01:02:56 +00001878PyObject *
1879PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001880{
1881 size_t size = strlen(u);
1882 if (size > PY_SSIZE_T_MAX) {
1883 PyErr_SetString(PyExc_OverflowError, "input too long");
1884 return NULL;
1885 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001886 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001887}
1888
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001889PyObject *
1890_PyUnicode_FromId(_Py_Identifier *id)
1891{
1892 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001893 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1894 strlen(id->string),
1895 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001896 if (!id->object)
1897 return NULL;
1898 PyUnicode_InternInPlace(&id->object);
1899 assert(!id->next);
1900 id->next = static_strings;
1901 static_strings = id;
1902 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001903 return id->object;
1904}
1905
1906void
1907_PyUnicode_ClearStaticStrings()
1908{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001909 _Py_Identifier *tmp, *s = static_strings;
1910 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001911 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 tmp = s->next;
1913 s->next = NULL;
1914 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001915 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001916 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001917}
1918
Benjamin Peterson0df54292012-03-26 14:50:32 -04001919/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001920
Victor Stinnerd3f08822012-05-29 12:57:52 +02001921PyObject*
1922_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001923{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001924 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001925 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001926 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001927#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001928 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001929#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001930 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001931 }
Victor Stinner785938e2011-12-11 20:09:03 +01001932 unicode = PyUnicode_New(size, 127);
1933 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001934 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001935 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1936 assert(_PyUnicode_CheckConsistency(unicode, 1));
1937 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001938}
1939
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940static Py_UCS4
1941kind_maxchar_limit(unsigned int kind)
1942{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001943 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001944 case PyUnicode_1BYTE_KIND:
1945 return 0x80;
1946 case PyUnicode_2BYTE_KIND:
1947 return 0x100;
1948 case PyUnicode_4BYTE_KIND:
1949 return 0x10000;
1950 default:
1951 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001952 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001953 }
1954}
1955
Victor Stinnere6abb482012-05-02 01:15:40 +02001956Py_LOCAL_INLINE(Py_UCS4)
1957align_maxchar(Py_UCS4 maxchar)
1958{
1959 if (maxchar <= 127)
1960 return 127;
1961 else if (maxchar <= 255)
1962 return 255;
1963 else if (maxchar <= 65535)
1964 return 65535;
1965 else
1966 return MAX_UNICODE;
1967}
1968
Victor Stinner702c7342011-10-05 13:50:52 +02001969static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001970_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001971{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001972 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001974
Serhiy Storchaka678db842013-01-26 12:16:36 +02001975 if (size == 0)
1976 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001977 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001978 if (size == 1)
1979 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001980
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001981 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001982 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 if (!res)
1984 return NULL;
1985 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001986 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001987 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001988}
1989
Victor Stinnere57b1c02011-09-28 22:20:48 +02001990static PyObject*
1991_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992{
1993 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001995
Serhiy Storchaka678db842013-01-26 12:16:36 +02001996 if (size == 0)
1997 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001998 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001999 if (size == 1)
2000 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002001
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002002 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002003 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 if (!res)
2005 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002006 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002008 else {
2009 _PyUnicode_CONVERT_BYTES(
2010 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2011 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002012 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 return res;
2014}
2015
Victor Stinnere57b1c02011-09-28 22:20:48 +02002016static PyObject*
2017_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018{
2019 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002021
Serhiy Storchaka678db842013-01-26 12:16:36 +02002022 if (size == 0)
2023 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002024 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002025 if (size == 1)
2026 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002027
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002028 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002029 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002030 if (!res)
2031 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002032 if (max_char < 256)
2033 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2034 PyUnicode_1BYTE_DATA(res));
2035 else if (max_char < 0x10000)
2036 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2037 PyUnicode_2BYTE_DATA(res));
2038 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002039 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002040 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return res;
2042}
2043
2044PyObject*
2045PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2046{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002047 if (size < 0) {
2048 PyErr_SetString(PyExc_ValueError, "size must be positive");
2049 return NULL;
2050 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002051 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002054 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002055 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002057 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002058 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002059 PyErr_SetString(PyExc_SystemError, "invalid kind");
2060 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002062}
2063
Victor Stinnerece58de2012-04-23 23:36:38 +02002064Py_UCS4
2065_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2066{
2067 enum PyUnicode_Kind kind;
2068 void *startptr, *endptr;
2069
2070 assert(PyUnicode_IS_READY(unicode));
2071 assert(0 <= start);
2072 assert(end <= PyUnicode_GET_LENGTH(unicode));
2073 assert(start <= end);
2074
2075 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2076 return PyUnicode_MAX_CHAR_VALUE(unicode);
2077
2078 if (start == end)
2079 return 127;
2080
Victor Stinner94d558b2012-04-27 22:26:58 +02002081 if (PyUnicode_IS_ASCII(unicode))
2082 return 127;
2083
Victor Stinnerece58de2012-04-23 23:36:38 +02002084 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002085 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002086 endptr = (char *)startptr + end * kind;
2087 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002088 switch(kind) {
2089 case PyUnicode_1BYTE_KIND:
2090 return ucs1lib_find_max_char(startptr, endptr);
2091 case PyUnicode_2BYTE_KIND:
2092 return ucs2lib_find_max_char(startptr, endptr);
2093 case PyUnicode_4BYTE_KIND:
2094 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002095 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002096 assert(0);
2097 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002098 }
2099}
2100
Victor Stinner25a4b292011-10-06 12:31:55 +02002101/* Ensure that a string uses the most efficient storage, if it is not the
2102 case: create a new string with of the right kind. Write NULL into *p_unicode
2103 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002104static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002105unicode_adjust_maxchar(PyObject **p_unicode)
2106{
2107 PyObject *unicode, *copy;
2108 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002109 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002110 unsigned int kind;
2111
2112 assert(p_unicode != NULL);
2113 unicode = *p_unicode;
2114 assert(PyUnicode_IS_READY(unicode));
2115 if (PyUnicode_IS_ASCII(unicode))
2116 return;
2117
2118 len = PyUnicode_GET_LENGTH(unicode);
2119 kind = PyUnicode_KIND(unicode);
2120 if (kind == PyUnicode_1BYTE_KIND) {
2121 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002122 max_char = ucs1lib_find_max_char(u, u + len);
2123 if (max_char >= 128)
2124 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002125 }
2126 else if (kind == PyUnicode_2BYTE_KIND) {
2127 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002128 max_char = ucs2lib_find_max_char(u, u + len);
2129 if (max_char >= 256)
2130 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002131 }
2132 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002133 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002135 max_char = ucs4lib_find_max_char(u, u + len);
2136 if (max_char >= 0x10000)
2137 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002139 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002140 if (copy != NULL)
2141 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002142 Py_DECREF(unicode);
2143 *p_unicode = copy;
2144}
2145
Victor Stinner034f6cf2011-09-30 02:26:44 +02002146PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002147_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148{
Victor Stinner87af4f22011-11-21 23:03:47 +01002149 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002150 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002151
Victor Stinner034f6cf2011-09-30 02:26:44 +02002152 if (!PyUnicode_Check(unicode)) {
2153 PyErr_BadInternalCall();
2154 return NULL;
2155 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002156 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002157 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002158
Victor Stinner87af4f22011-11-21 23:03:47 +01002159 length = PyUnicode_GET_LENGTH(unicode);
2160 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002161 if (!copy)
2162 return NULL;
2163 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2164
Victor Stinner87af4f22011-11-21 23:03:47 +01002165 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2166 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002167 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002168 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002169}
2170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171
Victor Stinnerbc603d12011-10-02 01:00:40 +02002172/* Widen Unicode objects to larger buffers. Don't write terminating null
2173 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174
2175void*
2176_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2177{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002178 Py_ssize_t len;
2179 void *result;
2180 unsigned int skind;
2181
Benjamin Petersonbac79492012-01-14 13:34:47 -05002182 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002183 return NULL;
2184
2185 len = PyUnicode_GET_LENGTH(s);
2186 skind = PyUnicode_KIND(s);
2187 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002188 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002189 return NULL;
2190 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002191 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002192 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002193 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002194 if (!result)
2195 return PyErr_NoMemory();
2196 assert(skind == PyUnicode_1BYTE_KIND);
2197 _PyUnicode_CONVERT_BYTES(
2198 Py_UCS1, Py_UCS2,
2199 PyUnicode_1BYTE_DATA(s),
2200 PyUnicode_1BYTE_DATA(s) + len,
2201 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002203 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002204 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002205 if (!result)
2206 return PyErr_NoMemory();
2207 if (skind == PyUnicode_2BYTE_KIND) {
2208 _PyUnicode_CONVERT_BYTES(
2209 Py_UCS2, Py_UCS4,
2210 PyUnicode_2BYTE_DATA(s),
2211 PyUnicode_2BYTE_DATA(s) + len,
2212 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002214 else {
2215 assert(skind == PyUnicode_1BYTE_KIND);
2216 _PyUnicode_CONVERT_BYTES(
2217 Py_UCS1, Py_UCS4,
2218 PyUnicode_1BYTE_DATA(s),
2219 PyUnicode_1BYTE_DATA(s) + len,
2220 result);
2221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002223 default:
2224 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 }
Victor Stinner01698042011-10-04 00:04:26 +02002226 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 return NULL;
2228}
2229
2230static Py_UCS4*
2231as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2232 int copy_null)
2233{
2234 int kind;
2235 void *data;
2236 Py_ssize_t len, targetlen;
2237 if (PyUnicode_READY(string) == -1)
2238 return NULL;
2239 kind = PyUnicode_KIND(string);
2240 data = PyUnicode_DATA(string);
2241 len = PyUnicode_GET_LENGTH(string);
2242 targetlen = len;
2243 if (copy_null)
2244 targetlen++;
2245 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002246 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002247 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;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002855 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002856 if (buffer == NULL) {
2857 PyErr_NoMemory();
2858 return NULL;
2859 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002860 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002861 if (buflen == -1) {
2862 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002863 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002864 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002865 if (size != NULL)
2866 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002867 return buffer;
2868}
2869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002871
Alexander Belopolsky40018472011-02-26 01:02:56 +00002872PyObject *
2873PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002874{
Victor Stinner8faf8212011-12-08 22:14:11 +01002875 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002876 PyErr_SetString(PyExc_ValueError,
2877 "chr() arg not in range(0x110000)");
2878 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002879 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002880
Victor Stinner985a82a2014-01-03 12:53:47 +01002881 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002882}
2883
Alexander Belopolsky40018472011-02-26 01:02:56 +00002884PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002885PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002887 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002888 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002889 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002890 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002891 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002892 Py_INCREF(obj);
2893 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 }
2895 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002896 /* For a Unicode subtype that's not a Unicode object,
2897 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002898 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002899 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002900 PyErr_Format(PyExc_TypeError,
2901 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002902 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002903 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002904}
2905
Alexander Belopolsky40018472011-02-26 01:02:56 +00002906PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002907PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002908 const char *encoding,
2909 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002910{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002911 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002912 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002913
Guido van Rossumd57fd912000-03-10 22:53:23 +00002914 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002915 PyErr_BadInternalCall();
2916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002918
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002919 /* Decoding bytes objects is the most common case and should be fast */
2920 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002921 if (PyBytes_GET_SIZE(obj) == 0)
2922 _Py_RETURN_UNICODE_EMPTY();
2923 v = PyUnicode_Decode(
2924 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2925 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002926 return v;
2927 }
2928
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002929 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002930 PyErr_SetString(PyExc_TypeError,
2931 "decoding str is not supported");
2932 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002933 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002934
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002935 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2936 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2937 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002938 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002939 Py_TYPE(obj)->tp_name);
2940 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002941 }
Tim Petersced69f82003-09-16 20:30:58 +00002942
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002943 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002944 PyBuffer_Release(&buffer);
2945 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002947
Serhiy Storchaka05997252013-01-26 12:14:02 +02002948 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002949 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002950 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951}
2952
Victor Stinner600d3be2010-06-10 12:00:55 +00002953/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002954 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2955 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002956int
2957_Py_normalize_encoding(const char *encoding,
2958 char *lower,
2959 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002960{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002961 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002962 char *l;
2963 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002964
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002965 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002966 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002967 if (lower_len < 6)
2968 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002969 strcpy(lower, "utf-8");
2970 return 1;
2971 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002972 e = encoding;
2973 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002974 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002975 while (*e) {
2976 if (l == l_end)
2977 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002978 if (Py_ISUPPER(*e)) {
2979 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002980 }
2981 else if (*e == '_') {
2982 *l++ = '-';
2983 e++;
2984 }
2985 else {
2986 *l++ = *e++;
2987 }
2988 }
2989 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002990 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002991}
2992
Alexander Belopolsky40018472011-02-26 01:02:56 +00002993PyObject *
2994PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002995 Py_ssize_t size,
2996 const char *encoding,
2997 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002998{
2999 PyObject *buffer = NULL, *unicode;
3000 Py_buffer info;
3001 char lower[11]; /* Enough for any encoding shortcut */
3002
Fred Drakee4315f52000-05-09 19:53:39 +00003003 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003004 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003005 if ((strcmp(lower, "utf-8") == 0) ||
3006 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003007 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003008 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003009 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003010 (strcmp(lower, "iso-8859-1") == 0) ||
3011 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003012 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003013#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003014 else if (strcmp(lower, "mbcs") == 0)
3015 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003016#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003017 else if (strcmp(lower, "ascii") == 0)
3018 return PyUnicode_DecodeASCII(s, size, errors);
3019 else if (strcmp(lower, "utf-16") == 0)
3020 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3021 else if (strcmp(lower, "utf-32") == 0)
3022 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3023 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024
3025 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003026 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003027 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003028 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003029 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030 if (buffer == NULL)
3031 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003032 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003033 if (unicode == NULL)
3034 goto onError;
3035 if (!PyUnicode_Check(unicode)) {
3036 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003037 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3038 "use codecs.decode() to decode to arbitrary types",
3039 encoding,
3040 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003041 Py_DECREF(unicode);
3042 goto onError;
3043 }
3044 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003045 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003046
Benjamin Peterson29060642009-01-31 22:14:21 +00003047 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003048 Py_XDECREF(buffer);
3049 return NULL;
3050}
3051
Alexander Belopolsky40018472011-02-26 01:02:56 +00003052PyObject *
3053PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003054 const char *encoding,
3055 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003056{
3057 PyObject *v;
3058
3059 if (!PyUnicode_Check(unicode)) {
3060 PyErr_BadArgument();
3061 goto onError;
3062 }
3063
3064 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003065 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003066
3067 /* Decode via the codec registry */
3068 v = PyCodec_Decode(unicode, encoding, errors);
3069 if (v == NULL)
3070 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003071 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003072
Benjamin Peterson29060642009-01-31 22:14:21 +00003073 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003074 return NULL;
3075}
3076
Alexander Belopolsky40018472011-02-26 01:02:56 +00003077PyObject *
3078PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003079 const char *encoding,
3080 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003081{
3082 PyObject *v;
3083
3084 if (!PyUnicode_Check(unicode)) {
3085 PyErr_BadArgument();
3086 goto onError;
3087 }
3088
3089 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003090 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003091
3092 /* Decode via the codec registry */
3093 v = PyCodec_Decode(unicode, encoding, errors);
3094 if (v == NULL)
3095 goto onError;
3096 if (!PyUnicode_Check(v)) {
3097 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003098 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3099 "use codecs.decode() to decode to arbitrary types",
3100 encoding,
3101 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003102 Py_DECREF(v);
3103 goto onError;
3104 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003105 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003106
Benjamin Peterson29060642009-01-31 22:14:21 +00003107 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003108 return NULL;
3109}
3110
Alexander Belopolsky40018472011-02-26 01:02:56 +00003111PyObject *
3112PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003113 Py_ssize_t size,
3114 const char *encoding,
3115 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116{
3117 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003118
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119 unicode = PyUnicode_FromUnicode(s, size);
3120 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003122 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3123 Py_DECREF(unicode);
3124 return v;
3125}
3126
Alexander Belopolsky40018472011-02-26 01:02:56 +00003127PyObject *
3128PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003129 const char *encoding,
3130 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003131{
3132 PyObject *v;
3133
3134 if (!PyUnicode_Check(unicode)) {
3135 PyErr_BadArgument();
3136 goto onError;
3137 }
3138
3139 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003140 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003141
3142 /* Encode via the codec registry */
3143 v = PyCodec_Encode(unicode, encoding, errors);
3144 if (v == NULL)
3145 goto onError;
3146 return v;
3147
Benjamin Peterson29060642009-01-31 22:14:21 +00003148 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003149 return NULL;
3150}
3151
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003152static size_t
3153wcstombs_errorpos(const wchar_t *wstr)
3154{
3155 size_t len;
3156#if SIZEOF_WCHAR_T == 2
3157 wchar_t buf[3];
3158#else
3159 wchar_t buf[2];
3160#endif
3161 char outbuf[MB_LEN_MAX];
3162 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003163
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003164#if SIZEOF_WCHAR_T == 2
3165 buf[2] = 0;
3166#else
3167 buf[1] = 0;
3168#endif
3169 start = wstr;
3170 while (*wstr != L'\0')
3171 {
3172 previous = wstr;
3173#if SIZEOF_WCHAR_T == 2
3174 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3175 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3176 {
3177 buf[0] = wstr[0];
3178 buf[1] = wstr[1];
3179 wstr += 2;
3180 }
3181 else {
3182 buf[0] = *wstr;
3183 buf[1] = 0;
3184 wstr++;
3185 }
3186#else
3187 buf[0] = *wstr;
3188 wstr++;
3189#endif
3190 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003191 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003192 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003193 }
3194
3195 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003196 return 0;
3197}
3198
Victor Stinner1b579672011-12-17 05:47:23 +01003199static int
3200locale_error_handler(const char *errors, int *surrogateescape)
3201{
3202 if (errors == NULL) {
3203 *surrogateescape = 0;
3204 return 0;
3205 }
3206
3207 if (strcmp(errors, "strict") == 0) {
3208 *surrogateescape = 0;
3209 return 0;
3210 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003211 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003212 *surrogateescape = 1;
3213 return 0;
3214 }
3215 PyErr_Format(PyExc_ValueError,
3216 "only 'strict' and 'surrogateescape' error handlers "
3217 "are supported, not '%s'",
3218 errors);
3219 return -1;
3220}
3221
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003222PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003223PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003224{
3225 Py_ssize_t wlen, wlen2;
3226 wchar_t *wstr;
3227 PyObject *bytes = NULL;
3228 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003229 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003230 PyObject *exc;
3231 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003232 int surrogateescape;
3233
3234 if (locale_error_handler(errors, &surrogateescape) < 0)
3235 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236
3237 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3238 if (wstr == NULL)
3239 return NULL;
3240
3241 wlen2 = wcslen(wstr);
3242 if (wlen2 != wlen) {
3243 PyMem_Free(wstr);
3244 PyErr_SetString(PyExc_TypeError, "embedded null character");
3245 return NULL;
3246 }
3247
3248 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003249 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003250 char *str;
3251
3252 str = _Py_wchar2char(wstr, &error_pos);
3253 if (str == NULL) {
3254 if (error_pos == (size_t)-1) {
3255 PyErr_NoMemory();
3256 PyMem_Free(wstr);
3257 return NULL;
3258 }
3259 else {
3260 goto encode_error;
3261 }
3262 }
3263 PyMem_Free(wstr);
3264
3265 bytes = PyBytes_FromString(str);
3266 PyMem_Free(str);
3267 }
3268 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003269 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003270 size_t len, len2;
3271
3272 len = wcstombs(NULL, wstr, 0);
3273 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003274 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003275 goto encode_error;
3276 }
3277
3278 bytes = PyBytes_FromStringAndSize(NULL, len);
3279 if (bytes == NULL) {
3280 PyMem_Free(wstr);
3281 return NULL;
3282 }
3283
3284 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3285 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003286 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003287 goto encode_error;
3288 }
3289 PyMem_Free(wstr);
3290 }
3291 return bytes;
3292
3293encode_error:
3294 errmsg = strerror(errno);
3295 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003296
3297 if (error_pos == (size_t)-1)
3298 error_pos = wcstombs_errorpos(wstr);
3299
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003300 PyMem_Free(wstr);
3301 Py_XDECREF(bytes);
3302
Victor Stinner2f197072011-12-17 07:08:30 +01003303 if (errmsg != NULL) {
3304 size_t errlen;
3305 wstr = _Py_char2wchar(errmsg, &errlen);
3306 if (wstr != NULL) {
3307 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003308 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003309 } else
3310 errmsg = NULL;
3311 }
3312 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003313 reason = PyUnicode_FromString(
3314 "wcstombs() encountered an unencodable "
3315 "wide character");
3316 if (reason == NULL)
3317 return NULL;
3318
3319 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3320 "locale", unicode,
3321 (Py_ssize_t)error_pos,
3322 (Py_ssize_t)(error_pos+1),
3323 reason);
3324 Py_DECREF(reason);
3325 if (exc != NULL) {
3326 PyCodec_StrictErrors(exc);
3327 Py_XDECREF(exc);
3328 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003329 return NULL;
3330}
3331
Victor Stinnerad158722010-10-27 00:25:46 +00003332PyObject *
3333PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003334{
Victor Stinner99b95382011-07-04 14:23:54 +02003335#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003336 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003337#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003338 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003339#else
Victor Stinner793b5312011-04-27 00:24:21 +02003340 PyInterpreterState *interp = PyThreadState_GET()->interp;
3341 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3342 cannot use it to encode and decode filenames before it is loaded. Load
3343 the Python codec requires to encode at least its own filename. Use the C
3344 version of the locale codec until the codec registry is initialized and
3345 the Python codec is loaded.
3346
3347 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3348 cannot only rely on it: check also interp->fscodec_initialized for
3349 subinterpreters. */
3350 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003351 return PyUnicode_AsEncodedString(unicode,
3352 Py_FileSystemDefaultEncoding,
3353 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003354 }
3355 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003356 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003357 }
Victor Stinnerad158722010-10-27 00:25:46 +00003358#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003359}
3360
Alexander Belopolsky40018472011-02-26 01:02:56 +00003361PyObject *
3362PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003363 const char *encoding,
3364 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003365{
3366 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003367 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003368
Guido van Rossumd57fd912000-03-10 22:53:23 +00003369 if (!PyUnicode_Check(unicode)) {
3370 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003371 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003372 }
Fred Drakee4315f52000-05-09 19:53:39 +00003373
Fred Drakee4315f52000-05-09 19:53:39 +00003374 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003375 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003376 if ((strcmp(lower, "utf-8") == 0) ||
3377 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003378 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003379 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003380 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003381 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003382 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003383 }
Victor Stinner37296e82010-06-10 13:36:23 +00003384 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003385 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003386 (strcmp(lower, "iso-8859-1") == 0) ||
3387 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003389#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003390 else if (strcmp(lower, "mbcs") == 0)
3391 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003392#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003393 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003395 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003396
3397 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003398 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003399 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003400 return NULL;
3401
3402 /* The normal path */
3403 if (PyBytes_Check(v))
3404 return v;
3405
3406 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003407 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003408 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003409 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003410
3411 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003412 "encoder %s returned bytearray instead of bytes; "
3413 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003414 encoding);
3415 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003416 Py_DECREF(v);
3417 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003418 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003419
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003420 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3421 Py_DECREF(v);
3422 return b;
3423 }
3424
3425 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003426 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3427 "use codecs.encode() to encode to arbitrary types",
3428 encoding,
3429 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003430 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003431 return NULL;
3432}
3433
Alexander Belopolsky40018472011-02-26 01:02:56 +00003434PyObject *
3435PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003436 const char *encoding,
3437 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438{
3439 PyObject *v;
3440
3441 if (!PyUnicode_Check(unicode)) {
3442 PyErr_BadArgument();
3443 goto onError;
3444 }
3445
3446 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003447 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003448
3449 /* Encode via the codec registry */
3450 v = PyCodec_Encode(unicode, encoding, errors);
3451 if (v == NULL)
3452 goto onError;
3453 if (!PyUnicode_Check(v)) {
3454 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003455 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3456 "use codecs.encode() to encode to arbitrary types",
3457 encoding,
3458 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003459 Py_DECREF(v);
3460 goto onError;
3461 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003462 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003463
Benjamin Peterson29060642009-01-31 22:14:21 +00003464 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003465 return NULL;
3466}
3467
Victor Stinner2f197072011-12-17 07:08:30 +01003468static size_t
3469mbstowcs_errorpos(const char *str, size_t len)
3470{
3471#ifdef HAVE_MBRTOWC
3472 const char *start = str;
3473 mbstate_t mbs;
3474 size_t converted;
3475 wchar_t ch;
3476
3477 memset(&mbs, 0, sizeof mbs);
3478 while (len)
3479 {
3480 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3481 if (converted == 0)
3482 /* Reached end of string */
3483 break;
3484 if (converted == (size_t)-1 || converted == (size_t)-2) {
3485 /* Conversion error or incomplete character */
3486 return str - start;
3487 }
3488 else {
3489 str += converted;
3490 len -= converted;
3491 }
3492 }
3493 /* failed to find the undecodable byte sequence */
3494 return 0;
3495#endif
3496 return 0;
3497}
3498
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003499PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003500PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003501 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003502{
3503 wchar_t smallbuf[256];
3504 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3505 wchar_t *wstr;
3506 size_t wlen, wlen2;
3507 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003508 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003509 size_t error_pos;
3510 char *errmsg;
3511 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003512
3513 if (locale_error_handler(errors, &surrogateescape) < 0)
3514 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515
3516 if (str[len] != '\0' || len != strlen(str)) {
3517 PyErr_SetString(PyExc_TypeError, "embedded null character");
3518 return NULL;
3519 }
3520
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003521 if (surrogateescape) {
3522 /* "surrogateescape" error handler */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 wstr = _Py_char2wchar(str, &wlen);
3524 if (wstr == NULL) {
3525 if (wlen == (size_t)-1)
3526 PyErr_NoMemory();
3527 else
3528 PyErr_SetFromErrno(PyExc_OSError);
3529 return NULL;
3530 }
3531
3532 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003533 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003534 }
3535 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003536 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003537#ifndef HAVE_BROKEN_MBSTOWCS
3538 wlen = mbstowcs(NULL, str, 0);
3539#else
3540 wlen = len;
3541#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003542 if (wlen == (size_t)-1)
3543 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003544 if (wlen+1 <= smallbuf_len) {
3545 wstr = smallbuf;
3546 }
3547 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003548 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003549 if (!wstr)
3550 return PyErr_NoMemory();
3551 }
3552
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003553 wlen2 = mbstowcs(wstr, str, wlen+1);
3554 if (wlen2 == (size_t)-1) {
3555 if (wstr != smallbuf)
3556 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003557 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003558 }
3559#ifdef HAVE_BROKEN_MBSTOWCS
3560 assert(wlen2 == wlen);
3561#endif
3562 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3563 if (wstr != smallbuf)
3564 PyMem_Free(wstr);
3565 }
3566 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003567
3568decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003569 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003570 errmsg = strerror(errno);
3571 assert(errmsg != NULL);
3572
3573 error_pos = mbstowcs_errorpos(str, len);
3574 if (errmsg != NULL) {
3575 size_t errlen;
3576 wstr = _Py_char2wchar(errmsg, &errlen);
3577 if (wstr != NULL) {
3578 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003579 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003580 }
Victor Stinner2f197072011-12-17 07:08:30 +01003581 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003582 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003583 reason = PyUnicode_FromString(
3584 "mbstowcs() encountered an invalid multibyte sequence");
3585 if (reason == NULL)
3586 return NULL;
3587
3588 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3589 "locale", str, len,
3590 (Py_ssize_t)error_pos,
3591 (Py_ssize_t)(error_pos+1),
3592 reason);
3593 Py_DECREF(reason);
3594 if (exc != NULL) {
3595 PyCodec_StrictErrors(exc);
3596 Py_XDECREF(exc);
3597 }
3598 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003599}
3600
3601PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003602PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003603{
3604 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003605 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003606}
3607
3608
3609PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003610PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003611 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003612 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3613}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003614
Christian Heimes5894ba72007-11-04 11:43:14 +00003615PyObject*
3616PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3617{
Victor Stinner99b95382011-07-04 14:23:54 +02003618#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003619 return PyUnicode_DecodeMBCS(s, size, NULL);
3620#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003621 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003622#else
Victor Stinner793b5312011-04-27 00:24:21 +02003623 PyInterpreterState *interp = PyThreadState_GET()->interp;
3624 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3625 cannot use it to encode and decode filenames before it is loaded. Load
3626 the Python codec requires to encode at least its own filename. Use the C
3627 version of the locale codec until the codec registry is initialized and
3628 the Python codec is loaded.
3629
3630 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3631 cannot only rely on it: check also interp->fscodec_initialized for
3632 subinterpreters. */
3633 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003634 return PyUnicode_Decode(s, size,
3635 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003636 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003637 }
3638 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003639 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003640 }
Victor Stinnerad158722010-10-27 00:25:46 +00003641#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003642}
3643
Martin v. Löwis011e8422009-05-05 04:43:17 +00003644
3645int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003646_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003647{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003648 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003649
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003650 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003651 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003652 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3653 PyUnicode_GET_LENGTH(str), '\0', 1);
3654 if (pos == -1)
3655 return 0;
3656 else
3657 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003658}
3659
Antoine Pitrou13348842012-01-29 18:36:34 +01003660int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003661PyUnicode_FSConverter(PyObject* arg, void* addr)
3662{
3663 PyObject *output = NULL;
3664 Py_ssize_t size;
3665 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003666 if (arg == NULL) {
3667 Py_DECREF(*(PyObject**)addr);
3668 return 1;
3669 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003670 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003671 output = arg;
3672 Py_INCREF(output);
3673 }
3674 else {
3675 arg = PyUnicode_FromObject(arg);
3676 if (!arg)
3677 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003678 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003679 Py_DECREF(arg);
3680 if (!output)
3681 return 0;
3682 if (!PyBytes_Check(output)) {
3683 Py_DECREF(output);
3684 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3685 return 0;
3686 }
3687 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003688 size = PyBytes_GET_SIZE(output);
3689 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003690 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003691 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003692 Py_DECREF(output);
3693 return 0;
3694 }
3695 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003696 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003697}
3698
3699
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003700int
3701PyUnicode_FSDecoder(PyObject* arg, void* addr)
3702{
3703 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003704 if (arg == NULL) {
3705 Py_DECREF(*(PyObject**)addr);
3706 return 1;
3707 }
3708 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003709 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003710 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003711 output = arg;
3712 Py_INCREF(output);
3713 }
3714 else {
3715 arg = PyBytes_FromObject(arg);
3716 if (!arg)
3717 return 0;
3718 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3719 PyBytes_GET_SIZE(arg));
3720 Py_DECREF(arg);
3721 if (!output)
3722 return 0;
3723 if (!PyUnicode_Check(output)) {
3724 Py_DECREF(output);
3725 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3726 return 0;
3727 }
3728 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003729 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003730 Py_DECREF(output);
3731 return 0;
3732 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003733 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003734 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003735 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3736 Py_DECREF(output);
3737 return 0;
3738 }
3739 *(PyObject**)addr = output;
3740 return Py_CLEANUP_SUPPORTED;
3741}
3742
3743
Martin v. Löwis5b222132007-06-10 09:51:05 +00003744char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003745PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003746{
Christian Heimesf3863112007-11-22 07:46:41 +00003747 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003749 if (!PyUnicode_Check(unicode)) {
3750 PyErr_BadArgument();
3751 return NULL;
3752 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003753 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003754 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003755
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003756 if (PyUnicode_UTF8(unicode) == NULL) {
3757 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003758 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3759 if (bytes == NULL)
3760 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003761 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3762 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003763 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764 Py_DECREF(bytes);
3765 return NULL;
3766 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003767 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3768 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3769 PyBytes_AS_STRING(bytes),
3770 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771 Py_DECREF(bytes);
3772 }
3773
3774 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003775 *psize = PyUnicode_UTF8_LENGTH(unicode);
3776 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003777}
3778
3779char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003781{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003782 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3783}
3784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003785Py_UNICODE *
3786PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3787{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788 const unsigned char *one_byte;
3789#if SIZEOF_WCHAR_T == 4
3790 const Py_UCS2 *two_bytes;
3791#else
3792 const Py_UCS4 *four_bytes;
3793 const Py_UCS4 *ucs4_end;
3794 Py_ssize_t num_surrogates;
3795#endif
3796 wchar_t *w;
3797 wchar_t *wchar_end;
3798
3799 if (!PyUnicode_Check(unicode)) {
3800 PyErr_BadArgument();
3801 return NULL;
3802 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003804 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003805 assert(_PyUnicode_KIND(unicode) != 0);
3806 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003807
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003810 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3811 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 num_surrogates = 0;
3813
3814 for (; four_bytes < ucs4_end; ++four_bytes) {
3815 if (*four_bytes > 0xFFFF)
3816 ++num_surrogates;
3817 }
3818
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3820 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3821 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 PyErr_NoMemory();
3823 return NULL;
3824 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003825 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003827 w = _PyUnicode_WSTR(unicode);
3828 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3829 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3831 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003832 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003834 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3835 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003836 }
3837 else
3838 *w = *four_bytes;
3839
3840 if (w > wchar_end) {
3841 assert(0 && "Miscalculated string end");
3842 }
3843 }
3844 *w = 0;
3845#else
3846 /* sizeof(wchar_t) == 4 */
3847 Py_FatalError("Impossible unicode object state, wstr and str "
3848 "should share memory already.");
3849 return NULL;
3850#endif
3851 }
3852 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003853 if ((size_t)_PyUnicode_LENGTH(unicode) >
3854 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3855 PyErr_NoMemory();
3856 return NULL;
3857 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003858 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3859 (_PyUnicode_LENGTH(unicode) + 1));
3860 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861 PyErr_NoMemory();
3862 return NULL;
3863 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003864 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3865 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3866 w = _PyUnicode_WSTR(unicode);
3867 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003868
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3870 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 for (; w < wchar_end; ++one_byte, ++w)
3872 *w = *one_byte;
3873 /* null-terminate the wstr */
3874 *w = 0;
3875 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003876 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003877#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003878 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003879 for (; w < wchar_end; ++two_bytes, ++w)
3880 *w = *two_bytes;
3881 /* null-terminate the wstr */
3882 *w = 0;
3883#else
3884 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003885 PyObject_FREE(_PyUnicode_WSTR(unicode));
3886 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887 Py_FatalError("Impossible unicode object state, wstr "
3888 "and str should share memory already.");
3889 return NULL;
3890#endif
3891 }
3892 else {
3893 assert(0 && "This should never happen.");
3894 }
3895 }
3896 }
3897 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003898 *size = PyUnicode_WSTR_LENGTH(unicode);
3899 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003900}
3901
Alexander Belopolsky40018472011-02-26 01:02:56 +00003902Py_UNICODE *
3903PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003905 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003906}
3907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908
Alexander Belopolsky40018472011-02-26 01:02:56 +00003909Py_ssize_t
3910PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003911{
3912 if (!PyUnicode_Check(unicode)) {
3913 PyErr_BadArgument();
3914 goto onError;
3915 }
3916 return PyUnicode_GET_SIZE(unicode);
3917
Benjamin Peterson29060642009-01-31 22:14:21 +00003918 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003919 return -1;
3920}
3921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003922Py_ssize_t
3923PyUnicode_GetLength(PyObject *unicode)
3924{
Victor Stinner07621332012-06-16 04:53:46 +02003925 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 PyErr_BadArgument();
3927 return -1;
3928 }
Victor Stinner07621332012-06-16 04:53:46 +02003929 if (PyUnicode_READY(unicode) == -1)
3930 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003931 return PyUnicode_GET_LENGTH(unicode);
3932}
3933
3934Py_UCS4
3935PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3936{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003937 void *data;
3938 int kind;
3939
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003940 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3941 PyErr_BadArgument();
3942 return (Py_UCS4)-1;
3943 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003944 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003945 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003946 return (Py_UCS4)-1;
3947 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003948 data = PyUnicode_DATA(unicode);
3949 kind = PyUnicode_KIND(unicode);
3950 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003951}
3952
3953int
3954PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3955{
3956 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003957 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003958 return -1;
3959 }
Victor Stinner488fa492011-12-12 00:01:39 +01003960 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003961 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003962 PyErr_SetString(PyExc_IndexError, "string index out of range");
3963 return -1;
3964 }
Victor Stinner488fa492011-12-12 00:01:39 +01003965 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003966 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003967 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3968 PyErr_SetString(PyExc_ValueError, "character out of range");
3969 return -1;
3970 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3972 index, ch);
3973 return 0;
3974}
3975
Alexander Belopolsky40018472011-02-26 01:02:56 +00003976const char *
3977PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003978{
Victor Stinner42cb4622010-09-01 19:39:01 +00003979 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003980}
3981
Victor Stinner554f3f02010-06-16 23:33:54 +00003982/* create or adjust a UnicodeDecodeError */
3983static void
3984make_decode_exception(PyObject **exceptionObject,
3985 const char *encoding,
3986 const char *input, Py_ssize_t length,
3987 Py_ssize_t startpos, Py_ssize_t endpos,
3988 const char *reason)
3989{
3990 if (*exceptionObject == NULL) {
3991 *exceptionObject = PyUnicodeDecodeError_Create(
3992 encoding, input, length, startpos, endpos, reason);
3993 }
3994 else {
3995 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3996 goto onError;
3997 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3998 goto onError;
3999 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4000 goto onError;
4001 }
4002 return;
4003
4004onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004005 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004006}
4007
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004008#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009/* error handling callback helper:
4010 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004011 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004012 and adjust various state variables.
4013 return 0 on success, -1 on error
4014*/
4015
Alexander Belopolsky40018472011-02-26 01:02:56 +00004016static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004017unicode_decode_call_errorhandler_wchar(
4018 const char *errors, PyObject **errorHandler,
4019 const char *encoding, const char *reason,
4020 const char **input, const char **inend, Py_ssize_t *startinpos,
4021 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4022 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004023{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004024 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025
4026 PyObject *restuple = NULL;
4027 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004028 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004029 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004030 Py_ssize_t requiredsize;
4031 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004032 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004033 wchar_t *repwstr;
4034 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004035
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004036 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4037 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004038
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 *errorHandler = PyCodec_LookupError(errors);
4041 if (*errorHandler == NULL)
4042 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004043 }
4044
Victor Stinner554f3f02010-06-16 23:33:54 +00004045 make_decode_exception(exceptionObject,
4046 encoding,
4047 *input, *inend - *input,
4048 *startinpos, *endinpos,
4049 reason);
4050 if (*exceptionObject == NULL)
4051 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004052
4053 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4054 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004056 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004057 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004058 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004059 }
4060 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004061 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004062
4063 /* Copy back the bytes variables, which might have been modified by the
4064 callback */
4065 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4066 if (!inputobj)
4067 goto onError;
4068 if (!PyBytes_Check(inputobj)) {
4069 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4070 }
4071 *input = PyBytes_AS_STRING(inputobj);
4072 insize = PyBytes_GET_SIZE(inputobj);
4073 *inend = *input + insize;
4074 /* we can DECREF safely, as the exception has another reference,
4075 so the object won't go away. */
4076 Py_DECREF(inputobj);
4077
4078 if (newpos<0)
4079 newpos = insize+newpos;
4080 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004081 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004082 goto onError;
4083 }
4084
4085 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4086 if (repwstr == NULL)
4087 goto onError;
4088 /* need more space? (at least enough for what we
4089 have+the replacement+the rest of the string (starting
4090 at the new input position), so we won't have to check space
4091 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004092 requiredsize = *outpos;
4093 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4094 goto overflow;
4095 requiredsize += repwlen;
4096 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4097 goto overflow;
4098 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004099 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004100 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004101 requiredsize = 2*outsize;
4102 if (unicode_resize(output, requiredsize) < 0)
4103 goto onError;
4104 }
4105 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4106 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004107 *endinpos = newpos;
4108 *inptr = *input + newpos;
4109
4110 /* we made it! */
4111 Py_XDECREF(restuple);
4112 return 0;
4113
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004114 overflow:
4115 PyErr_SetString(PyExc_OverflowError,
4116 "decoded result is too long for a Python string");
4117
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004118 onError:
4119 Py_XDECREF(restuple);
4120 return -1;
4121}
4122#endif /* HAVE_MBCS */
4123
4124static int
4125unicode_decode_call_errorhandler_writer(
4126 const char *errors, PyObject **errorHandler,
4127 const char *encoding, const char *reason,
4128 const char **input, const char **inend, Py_ssize_t *startinpos,
4129 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4130 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4131{
4132 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4133
4134 PyObject *restuple = NULL;
4135 PyObject *repunicode = NULL;
4136 Py_ssize_t insize;
4137 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004138 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004139 PyObject *inputobj = NULL;
4140
4141 if (*errorHandler == NULL) {
4142 *errorHandler = PyCodec_LookupError(errors);
4143 if (*errorHandler == NULL)
4144 goto onError;
4145 }
4146
4147 make_decode_exception(exceptionObject,
4148 encoding,
4149 *input, *inend - *input,
4150 *startinpos, *endinpos,
4151 reason);
4152 if (*exceptionObject == NULL)
4153 goto onError;
4154
4155 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4156 if (restuple == NULL)
4157 goto onError;
4158 if (!PyTuple_Check(restuple)) {
4159 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4160 goto onError;
4161 }
4162 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004163 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004164
4165 /* Copy back the bytes variables, which might have been modified by the
4166 callback */
4167 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4168 if (!inputobj)
4169 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004170 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004171 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004172 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004173 *input = PyBytes_AS_STRING(inputobj);
4174 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004175 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004176 /* we can DECREF safely, as the exception has another reference,
4177 so the object won't go away. */
4178 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004179
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004180 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004181 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004182 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004183 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004184 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004185 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004186
Victor Stinner8f674cc2013-04-17 23:02:17 +02004187 if (PyUnicode_READY(repunicode) < 0)
4188 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004189 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004190 if (replen > 1) {
4191 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004192 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004193 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4194 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4195 goto onError;
4196 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004197 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004198 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004199
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004200 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004201 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004202
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004203 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004204 Py_XDECREF(restuple);
4205 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004206
Benjamin Peterson29060642009-01-31 22:14:21 +00004207 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004208 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004209 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004210}
4211
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004212/* --- UTF-7 Codec -------------------------------------------------------- */
4213
Antoine Pitrou244651a2009-05-04 18:56:13 +00004214/* See RFC2152 for details. We encode conservatively and decode liberally. */
4215
4216/* Three simple macros defining base-64. */
4217
4218/* Is c a base-64 character? */
4219
4220#define IS_BASE64(c) \
4221 (((c) >= 'A' && (c) <= 'Z') || \
4222 ((c) >= 'a' && (c) <= 'z') || \
4223 ((c) >= '0' && (c) <= '9') || \
4224 (c) == '+' || (c) == '/')
4225
4226/* given that c is a base-64 character, what is its base-64 value? */
4227
4228#define FROM_BASE64(c) \
4229 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4230 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4231 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4232 (c) == '+' ? 62 : 63)
4233
4234/* What is the base-64 character of the bottom 6 bits of n? */
4235
4236#define TO_BASE64(n) \
4237 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4238
4239/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4240 * decoded as itself. We are permissive on decoding; the only ASCII
4241 * byte not decoding to itself is the + which begins a base64
4242 * string. */
4243
4244#define DECODE_DIRECT(c) \
4245 ((c) <= 127 && (c) != '+')
4246
4247/* The UTF-7 encoder treats ASCII characters differently according to
4248 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4249 * the above). See RFC2152. This array identifies these different
4250 * sets:
4251 * 0 : "Set D"
4252 * alphanumeric and '(),-./:?
4253 * 1 : "Set O"
4254 * !"#$%&*;<=>@[]^_`{|}
4255 * 2 : "whitespace"
4256 * ht nl cr sp
4257 * 3 : special (must be base64 encoded)
4258 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4259 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004260
Tim Petersced69f82003-09-16 20:30:58 +00004261static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004262char utf7_category[128] = {
4263/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4264 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4265/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4266 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4267/* sp ! " # $ % & ' ( ) * + , - . / */
4268 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4269/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4271/* @ A B C D E F G H I J K L M N O */
4272 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4273/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4275/* ` a b c d e f g h i j k l m n o */
4276 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4277/* p q r s t u v w x y z { | } ~ del */
4278 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004279};
4280
Antoine Pitrou244651a2009-05-04 18:56:13 +00004281/* ENCODE_DIRECT: this character should be encoded as itself. The
4282 * answer depends on whether we are encoding set O as itself, and also
4283 * on whether we are encoding whitespace as itself. RFC2152 makes it
4284 * clear that the answers to these questions vary between
4285 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004286
Antoine Pitrou244651a2009-05-04 18:56:13 +00004287#define ENCODE_DIRECT(c, directO, directWS) \
4288 ((c) < 128 && (c) > 0 && \
4289 ((utf7_category[(c)] == 0) || \
4290 (directWS && (utf7_category[(c)] == 2)) || \
4291 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004292
Alexander Belopolsky40018472011-02-26 01:02:56 +00004293PyObject *
4294PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004295 Py_ssize_t size,
4296 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004297{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004298 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4299}
4300
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301/* The decoder. The only state we preserve is our read position,
4302 * i.e. how many characters we have consumed. So if we end in the
4303 * middle of a shift sequence we have to back off the read position
4304 * and the output to the beginning of the sequence, otherwise we lose
4305 * all the shift state (seen bits, number of bits seen, high
4306 * surrogate). */
4307
Alexander Belopolsky40018472011-02-26 01:02:56 +00004308PyObject *
4309PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004310 Py_ssize_t size,
4311 const char *errors,
4312 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004313{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004314 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004315 Py_ssize_t startinpos;
4316 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004317 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004318 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 const char *errmsg = "";
4320 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004322 unsigned int base64bits = 0;
4323 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004324 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004325 PyObject *errorHandler = NULL;
4326 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004328 if (size == 0) {
4329 if (consumed)
4330 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004331 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004332 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004334 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004335 _PyUnicodeWriter_Init(&writer);
4336 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004337
4338 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339 e = s + size;
4340
4341 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004344 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 if (inShift) { /* in a base-64 section */
4347 if (IS_BASE64(ch)) { /* consume a base-64 character */
4348 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4349 base64bits += 6;
4350 s++;
4351 if (base64bits >= 16) {
4352 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004353 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 base64bits -= 16;
4355 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004356 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004357 if (surrogate) {
4358 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004359 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4360 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004361 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004364 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004365 }
4366 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004367 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004368 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 }
Victor Stinner551ac952011-11-29 22:58:13 +01004372 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 /* first surrogate */
4374 surrogate = outCh;
4375 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004377 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004378 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 }
4380 }
4381 }
4382 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004384 if (base64bits > 0) { /* left-over bits */
4385 if (base64bits >= 6) {
4386 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004387 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388 errmsg = "partial character in shift sequence";
4389 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004391 else {
4392 /* Some bits remain; they should be zero */
4393 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004394 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004395 errmsg = "non-zero padding bits in shift sequence";
4396 goto utf7Error;
4397 }
4398 }
4399 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004400 if (surrogate && DECODE_DIRECT(ch)) {
4401 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4402 goto onError;
4403 }
4404 surrogate = 0;
4405 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 /* '-' is absorbed; other terminating
4407 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004408 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 }
4411 }
4412 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004414 s++; /* consume '+' */
4415 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004417 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004418 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 }
4420 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004421 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004422 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004423 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004425 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426 }
4427 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004428 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004429 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004430 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004431 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 else {
4434 startinpos = s-starts;
4435 s++;
4436 errmsg = "unexpected special character";
4437 goto utf7Error;
4438 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004441 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004442 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004443 errors, &errorHandler,
4444 "utf7", errmsg,
4445 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004446 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004448 }
4449
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 /* end of string */
4451
4452 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4453 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004454 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004455 if (surrogate ||
4456 (base64bits >= 6) ||
4457 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004458 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004459 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004460 errors, &errorHandler,
4461 "utf7", "unterminated shift sequence",
4462 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004463 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004464 goto onError;
4465 if (s < e)
4466 goto restart;
4467 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004468 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004469
4470 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004471 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004472 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004473 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004474 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004475 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004476 writer.kind, writer.data, shiftOutStart);
4477 Py_XDECREF(errorHandler);
4478 Py_XDECREF(exc);
4479 _PyUnicodeWriter_Dealloc(&writer);
4480 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004481 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004482 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004483 }
4484 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004485 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004487 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004489 Py_XDECREF(errorHandler);
4490 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004491 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492
Benjamin Peterson29060642009-01-31 22:14:21 +00004493 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004494 Py_XDECREF(errorHandler);
4495 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004496 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 return NULL;
4498}
4499
4500
Alexander Belopolsky40018472011-02-26 01:02:56 +00004501PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004502_PyUnicode_EncodeUTF7(PyObject *str,
4503 int base64SetO,
4504 int base64WhiteSpace,
4505 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004507 int kind;
4508 void *data;
4509 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004510 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004512 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513 unsigned int base64bits = 0;
4514 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515 char * out;
4516 char * start;
4517
Benjamin Petersonbac79492012-01-14 13:34:47 -05004518 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004519 return NULL;
4520 kind = PyUnicode_KIND(str);
4521 data = PyUnicode_DATA(str);
4522 len = PyUnicode_GET_LENGTH(str);
4523
4524 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004525 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004527 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004528 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004529 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004530 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531 if (v == NULL)
4532 return NULL;
4533
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004534 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004535 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004536 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004537
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 if (inShift) {
4539 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4540 /* shifting out */
4541 if (base64bits) { /* output remaining bits */
4542 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4543 base64buffer = 0;
4544 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 }
4546 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 /* Characters not in the BASE64 set implicitly unshift the sequence
4548 so no '-' is required, except if the character is itself a '-' */
4549 if (IS_BASE64(ch) || ch == '-') {
4550 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004551 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 *out++ = (char) ch;
4553 }
4554 else {
4555 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004556 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004557 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004558 else { /* not in a shift sequence */
4559 if (ch == '+') {
4560 *out++ = '+';
4561 *out++ = '-';
4562 }
4563 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4564 *out++ = (char) ch;
4565 }
4566 else {
4567 *out++ = '+';
4568 inShift = 1;
4569 goto encode_char;
4570 }
4571 }
4572 continue;
4573encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004575 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004576
Antoine Pitrou244651a2009-05-04 18:56:13 +00004577 /* code first surrogate */
4578 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004579 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 while (base64bits >= 6) {
4581 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4582 base64bits -= 6;
4583 }
4584 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004585 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004587 base64bits += 16;
4588 base64buffer = (base64buffer << 16) | ch;
4589 while (base64bits >= 6) {
4590 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4591 base64bits -= 6;
4592 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004593 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004594 if (base64bits)
4595 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4596 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004598 if (_PyBytes_Resize(&v, out - start) < 0)
4599 return NULL;
4600 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004601}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004602PyObject *
4603PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4604 Py_ssize_t size,
4605 int base64SetO,
4606 int base64WhiteSpace,
4607 const char *errors)
4608{
4609 PyObject *result;
4610 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4611 if (tmp == NULL)
4612 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004613 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004614 base64WhiteSpace, errors);
4615 Py_DECREF(tmp);
4616 return result;
4617}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619#undef IS_BASE64
4620#undef FROM_BASE64
4621#undef TO_BASE64
4622#undef DECODE_DIRECT
4623#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004624
Guido van Rossumd57fd912000-03-10 22:53:23 +00004625/* --- UTF-8 Codec -------------------------------------------------------- */
4626
Alexander Belopolsky40018472011-02-26 01:02:56 +00004627PyObject *
4628PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004629 Py_ssize_t size,
4630 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004631{
Walter Dörwald69652032004-09-07 20:24:22 +00004632 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4633}
4634
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635#include "stringlib/asciilib.h"
4636#include "stringlib/codecs.h"
4637#include "stringlib/undef.h"
4638
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004639#include "stringlib/ucs1lib.h"
4640#include "stringlib/codecs.h"
4641#include "stringlib/undef.h"
4642
4643#include "stringlib/ucs2lib.h"
4644#include "stringlib/codecs.h"
4645#include "stringlib/undef.h"
4646
4647#include "stringlib/ucs4lib.h"
4648#include "stringlib/codecs.h"
4649#include "stringlib/undef.h"
4650
Antoine Pitrouab868312009-01-10 15:40:25 +00004651/* Mask to quickly check whether a C 'long' contains a
4652 non-ASCII, UTF8-encoded char. */
4653#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004654# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004655#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004656# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004657#else
4658# error C 'long' size should be either 4 or 8!
4659#endif
4660
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661static Py_ssize_t
4662ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004663{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004664 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004665 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004666
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004667 /*
4668 * Issue #17237: m68k is a bit different from most architectures in
4669 * that objects do not use "natural alignment" - for example, int and
4670 * long are only aligned at 2-byte boundaries. Therefore the assert()
4671 * won't work; also, tests have shown that skipping the "optimised
4672 * version" will even speed up m68k.
4673 */
4674#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004675#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004676 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4677 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678 /* Fast path, see in STRINGLIB(utf8_decode) for
4679 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004680 /* Help allocation */
4681 const char *_p = p;
4682 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004683 while (_p < aligned_end) {
4684 unsigned long value = *(const unsigned long *) _p;
4685 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004686 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004687 *((unsigned long *)q) = value;
4688 _p += SIZEOF_LONG;
4689 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004690 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004691 p = _p;
4692 while (p < end) {
4693 if ((unsigned char)*p & 0x80)
4694 break;
4695 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004696 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004697 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004699#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004700#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004701 while (p < end) {
4702 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4703 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004704 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004705 /* Help allocation */
4706 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 while (_p < aligned_end) {
4708 unsigned long value = *(unsigned long *) _p;
4709 if (value & ASCII_CHAR_MASK)
4710 break;
4711 _p += SIZEOF_LONG;
4712 }
4713 p = _p;
4714 if (_p == end)
4715 break;
4716 }
4717 if ((unsigned char)*p & 0x80)
4718 break;
4719 ++p;
4720 }
4721 memcpy(dest, start, p - start);
4722 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004723}
Antoine Pitrouab868312009-01-10 15:40:25 +00004724
Victor Stinner785938e2011-12-11 20:09:03 +01004725PyObject *
4726PyUnicode_DecodeUTF8Stateful(const char *s,
4727 Py_ssize_t size,
4728 const char *errors,
4729 Py_ssize_t *consumed)
4730{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004731 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004732 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004733 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734
4735 Py_ssize_t startinpos;
4736 Py_ssize_t endinpos;
4737 const char *errmsg = "";
4738 PyObject *errorHandler = NULL;
4739 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004740
4741 if (size == 0) {
4742 if (consumed)
4743 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004744 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004745 }
4746
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004747 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4748 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004749 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 *consumed = 1;
4751 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004752 }
4753
Victor Stinner8f674cc2013-04-17 23:02:17 +02004754 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004755 writer.min_length = size;
4756 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004757 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004758
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004759 writer.pos = ascii_decode(s, end, writer.data);
4760 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004761 while (s < end) {
4762 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004763 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004765 if (PyUnicode_IS_ASCII(writer.buffer))
4766 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004768 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004769 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004770 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 } else {
4772 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004773 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 }
4775
4776 switch (ch) {
4777 case 0:
4778 if (s == end || consumed)
4779 goto End;
4780 errmsg = "unexpected end of data";
4781 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004782 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004783 break;
4784 case 1:
4785 errmsg = "invalid start byte";
4786 startinpos = s - starts;
4787 endinpos = startinpos + 1;
4788 break;
4789 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004790 case 3:
4791 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004792 errmsg = "invalid continuation byte";
4793 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004794 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004795 break;
4796 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004797 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798 goto onError;
4799 continue;
4800 }
4801
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004802 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004803 errors, &errorHandler,
4804 "utf-8", errmsg,
4805 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004806 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004807 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004808 }
4809
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004810End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004811 if (consumed)
4812 *consumed = s - starts;
4813
4814 Py_XDECREF(errorHandler);
4815 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004816 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004817
4818onError:
4819 Py_XDECREF(errorHandler);
4820 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004821 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004822 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004823}
4824
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004825#ifdef __APPLE__
4826
4827/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004828 used to decode the command line arguments on Mac OS X.
4829
4830 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004831 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004832
4833wchar_t*
4834_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4835{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 wchar_t *unicode;
4838 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004839
4840 /* Note: size will always be longer than the resulting Unicode
4841 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004842 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004843 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004844 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004845 if (!unicode)
4846 return NULL;
4847
4848 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004851 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004853#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004854 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004855#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004856 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004857#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858 if (ch > 0xFF) {
4859#if SIZEOF_WCHAR_T == 4
4860 assert(0);
4861#else
4862 assert(Py_UNICODE_IS_SURROGATE(ch));
4863 /* compute and append the two surrogates: */
4864 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4865 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4866#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004867 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004868 else {
4869 if (!ch && s == e)
4870 break;
4871 /* surrogateescape */
4872 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4873 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004874 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004875 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004876 return unicode;
4877}
4878
4879#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881/* Primary internal function which creates utf8 encoded bytes objects.
4882
4883 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004884 and allocate exactly as much space needed at the end. Else allocate the
4885 maximum possible needed (4 result bytes per Unicode character), and return
4886 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004887*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004888PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004889_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004890{
Victor Stinner6099a032011-12-18 14:22:26 +01004891 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004892 void *data;
4893 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004894
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895 if (!PyUnicode_Check(unicode)) {
4896 PyErr_BadArgument();
4897 return NULL;
4898 }
4899
4900 if (PyUnicode_READY(unicode) == -1)
4901 return NULL;
4902
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004903 if (PyUnicode_UTF8(unicode))
4904 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4905 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004906
4907 kind = PyUnicode_KIND(unicode);
4908 data = PyUnicode_DATA(unicode);
4909 size = PyUnicode_GET_LENGTH(unicode);
4910
Benjamin Petersonead6b532011-12-20 17:23:42 -06004911 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004912 default:
4913 assert(0);
4914 case PyUnicode_1BYTE_KIND:
4915 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4916 assert(!PyUnicode_IS_ASCII(unicode));
4917 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4918 case PyUnicode_2BYTE_KIND:
4919 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4920 case PyUnicode_4BYTE_KIND:
4921 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004923}
4924
Alexander Belopolsky40018472011-02-26 01:02:56 +00004925PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004926PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4927 Py_ssize_t size,
4928 const char *errors)
4929{
4930 PyObject *v, *unicode;
4931
4932 unicode = PyUnicode_FromUnicode(s, size);
4933 if (unicode == NULL)
4934 return NULL;
4935 v = _PyUnicode_AsUTF8String(unicode, errors);
4936 Py_DECREF(unicode);
4937 return v;
4938}
4939
4940PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004941PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004942{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004943 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004944}
4945
Walter Dörwald41980ca2007-08-16 21:55:45 +00004946/* --- UTF-32 Codec ------------------------------------------------------- */
4947
4948PyObject *
4949PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 Py_ssize_t size,
4951 const char *errors,
4952 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004953{
4954 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4955}
4956
4957PyObject *
4958PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 Py_ssize_t size,
4960 const char *errors,
4961 int *byteorder,
4962 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963{
4964 const char *starts = s;
4965 Py_ssize_t startinpos;
4966 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004967 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004968 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004969 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004970 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 PyObject *errorHandler = NULL;
4973 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004974
Walter Dörwald41980ca2007-08-16 21:55:45 +00004975 q = (unsigned char *)s;
4976 e = q + size;
4977
4978 if (byteorder)
4979 bo = *byteorder;
4980
4981 /* Check for BOM marks (U+FEFF) in the input and adjust current
4982 byte order setting accordingly. In native mode, the leading BOM
4983 mark is skipped, in all other modes, it is copied to the output
4984 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004985 if (bo == 0 && size >= 4) {
4986 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4987 if (bom == 0x0000FEFF) {
4988 bo = -1;
4989 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004990 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004991 else if (bom == 0xFFFE0000) {
4992 bo = 1;
4993 q += 4;
4994 }
4995 if (byteorder)
4996 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004997 }
4998
Victor Stinnere64322e2012-10-30 23:12:47 +01004999 if (q == e) {
5000 if (consumed)
5001 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005002 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005003 }
5004
Victor Stinnere64322e2012-10-30 23:12:47 +01005005#ifdef WORDS_BIGENDIAN
5006 le = bo < 0;
5007#else
5008 le = bo <= 0;
5009#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005010 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005011
Victor Stinner8f674cc2013-04-17 23:02:17 +02005012 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005013 writer.min_length = (e - q + 3) / 4;
5014 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005015 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005016
Victor Stinnere64322e2012-10-30 23:12:47 +01005017 while (1) {
5018 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005019 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005020
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005022 enum PyUnicode_Kind kind = writer.kind;
5023 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005024 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005025 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005026 if (le) {
5027 do {
5028 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5029 if (ch > maxch)
5030 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005031 if (kind != PyUnicode_1BYTE_KIND &&
5032 Py_UNICODE_IS_SURROGATE(ch))
5033 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005034 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005035 q += 4;
5036 } while (q <= last);
5037 }
5038 else {
5039 do {
5040 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5041 if (ch > maxch)
5042 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005043 if (kind != PyUnicode_1BYTE_KIND &&
5044 Py_UNICODE_IS_SURROGATE(ch))
5045 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005046 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005047 q += 4;
5048 } while (q <= last);
5049 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005050 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005051 }
5052
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005053 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005054 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005055 startinpos = ((const char *)q) - starts;
5056 endinpos = startinpos + 4;
5057 }
5058 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005059 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005060 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005061 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005062 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005063 startinpos = ((const char *)q) - starts;
5064 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005065 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005066 else {
5067 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005068 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005069 goto onError;
5070 q += 4;
5071 continue;
5072 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005073 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005074 startinpos = ((const char *)q) - starts;
5075 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005076 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005077
5078 /* The remaining input chars are ignored if the callback
5079 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005080 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005082 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005084 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005085 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 }
5087
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005089 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 Py_XDECREF(errorHandler);
5092 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005093 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005096 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097 Py_XDECREF(errorHandler);
5098 Py_XDECREF(exc);
5099 return NULL;
5100}
5101
5102PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005103_PyUnicode_EncodeUTF32(PyObject *str,
5104 const char *errors,
5105 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005107 int kind;
5108 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005109 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005110 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005111 unsigned char *p;
5112 Py_ssize_t nsize, i;
5113 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005114#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005115 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005116#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005117 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005118#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005119 const char *encoding;
5120 PyObject *errorHandler = NULL;
5121 PyObject *exc = NULL;
5122 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005123
Serhiy Storchaka30793282014-01-04 22:44:01 +02005124#define STORECHAR(CH) \
5125 do { \
5126 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5127 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5128 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5129 p[iorder[0]] = (CH) & 0xff; \
5130 p += 4; \
5131 } while(0)
5132
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005133 if (!PyUnicode_Check(str)) {
5134 PyErr_BadArgument();
5135 return NULL;
5136 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005137 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005138 return NULL;
5139 kind = PyUnicode_KIND(str);
5140 data = PyUnicode_DATA(str);
5141 len = PyUnicode_GET_LENGTH(str);
5142
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005143 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005144 if (nsize > PY_SSIZE_T_MAX / 4)
5145 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005146 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 if (v == NULL)
5148 return NULL;
5149
Serhiy Storchaka30793282014-01-04 22:44:01 +02005150 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005151 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005152 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005153 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005154 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005155
Serhiy Storchaka30793282014-01-04 22:44:01 +02005156 if (byteorder == -1) {
5157 /* force LE */
5158 iorder[0] = 0;
5159 iorder[1] = 1;
5160 iorder[2] = 2;
5161 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005162 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005163 }
5164 else if (byteorder == 1) {
5165 /* force BE */
5166 iorder[0] = 3;
5167 iorder[1] = 2;
5168 iorder[2] = 1;
5169 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005170 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005171 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005172 else
5173 encoding = "utf-32";
5174
5175 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005176 for (i = 0; i < len; i++)
5177 STORECHAR(PyUnicode_READ(kind, data, i));
5178 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179 }
5180
Serhiy Storchaka30793282014-01-04 22:44:01 +02005181 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005182 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005183 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5184 i++;
5185 assert(ch <= MAX_UNICODE);
5186 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5187 STORECHAR(ch);
5188 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005189 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005190
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005191 rep = unicode_encode_call_errorhandler(
5192 errors, &errorHandler,
5193 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005194 str, &exc, i-1, i, &i);
5195
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005196 if (!rep)
5197 goto error;
5198
5199 if (PyBytes_Check(rep)) {
5200 repsize = PyBytes_GET_SIZE(rep);
5201 if (repsize & 3) {
5202 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005203 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005204 "surrogates not allowed");
5205 goto error;
5206 }
5207 moreunits = repsize / 4;
5208 }
5209 else {
5210 assert(PyUnicode_Check(rep));
5211 if (PyUnicode_READY(rep) < 0)
5212 goto error;
5213 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5214 if (!PyUnicode_IS_ASCII(rep)) {
5215 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005216 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005217 "surrogates not allowed");
5218 goto error;
5219 }
5220 }
5221
5222 /* four bytes are reserved for each surrogate */
5223 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005224 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005225 Py_ssize_t morebytes = 4 * (moreunits - 1);
5226 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5227 /* integer overflow */
5228 PyErr_NoMemory();
5229 goto error;
5230 }
5231 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5232 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005233 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005234 }
5235
5236 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005237 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5238 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005239 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005240 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005241 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005242 repdata = PyUnicode_1BYTE_DATA(rep);
5243 while (repsize--) {
5244 Py_UCS4 ch = *repdata++;
5245 STORECHAR(ch);
5246 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005247 }
5248
5249 Py_CLEAR(rep);
5250 }
5251
5252 /* Cut back to size actually needed. This is necessary for, for example,
5253 encoding of a string containing isolated surrogates and the 'ignore'
5254 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005255 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005256 if (nsize != PyBytes_GET_SIZE(v))
5257 _PyBytes_Resize(&v, nsize);
5258 Py_XDECREF(errorHandler);
5259 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005260 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005261 error:
5262 Py_XDECREF(rep);
5263 Py_XDECREF(errorHandler);
5264 Py_XDECREF(exc);
5265 Py_XDECREF(v);
5266 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005267#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005268}
5269
Alexander Belopolsky40018472011-02-26 01:02:56 +00005270PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005271PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5272 Py_ssize_t size,
5273 const char *errors,
5274 int byteorder)
5275{
5276 PyObject *result;
5277 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5278 if (tmp == NULL)
5279 return NULL;
5280 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5281 Py_DECREF(tmp);
5282 return result;
5283}
5284
5285PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005286PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287{
Victor Stinnerb960b342011-11-20 19:12:52 +01005288 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005289}
5290
Guido van Rossumd57fd912000-03-10 22:53:23 +00005291/* --- UTF-16 Codec ------------------------------------------------------- */
5292
Tim Peters772747b2001-08-09 22:21:55 +00005293PyObject *
5294PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005295 Py_ssize_t size,
5296 const char *errors,
5297 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005298{
Walter Dörwald69652032004-09-07 20:24:22 +00005299 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5300}
5301
5302PyObject *
5303PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005304 Py_ssize_t size,
5305 const char *errors,
5306 int *byteorder,
5307 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005308{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005309 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005310 Py_ssize_t startinpos;
5311 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005312 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005313 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005314 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005316 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005317 PyObject *errorHandler = NULL;
5318 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005319 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005320
Tim Peters772747b2001-08-09 22:21:55 +00005321 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005322 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005323
5324 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005325 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005326
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005327 /* Check for BOM marks (U+FEFF) in the input and adjust current
5328 byte order setting accordingly. In native mode, the leading BOM
5329 mark is skipped, in all other modes, it is copied to the output
5330 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005331 if (bo == 0 && size >= 2) {
5332 const Py_UCS4 bom = (q[1] << 8) | q[0];
5333 if (bom == 0xFEFF) {
5334 q += 2;
5335 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005337 else if (bom == 0xFFFE) {
5338 q += 2;
5339 bo = 1;
5340 }
5341 if (byteorder)
5342 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005343 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005344
Antoine Pitrou63065d72012-05-15 23:48:04 +02005345 if (q == e) {
5346 if (consumed)
5347 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005348 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005349 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005350
Christian Heimes743e0cd2012-10-17 23:52:17 +02005351#if PY_LITTLE_ENDIAN
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-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005354#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005355 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005356 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005357#endif
Tim Peters772747b2001-08-09 22:21:55 +00005358
Antoine Pitrou63065d72012-05-15 23:48:04 +02005359 /* Note: size will always be longer than the resulting Unicode
5360 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005361 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005362 writer.min_length = (e - q + 1) / 2;
5363 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005364 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005365
Antoine Pitrou63065d72012-05-15 23:48:04 +02005366 while (1) {
5367 Py_UCS4 ch = 0;
5368 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005369 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005370 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005371 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005372 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005373 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005374 native_ordering);
5375 else
5376 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005377 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005378 native_ordering);
5379 } else if (kind == PyUnicode_2BYTE_KIND) {
5380 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005381 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005382 native_ordering);
5383 } else {
5384 assert(kind == PyUnicode_4BYTE_KIND);
5385 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005386 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005387 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005388 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005389 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005390
Antoine Pitrou63065d72012-05-15 23:48:04 +02005391 switch (ch)
5392 {
5393 case 0:
5394 /* remaining byte at the end? (size should be even) */
5395 if (q == e || consumed)
5396 goto End;
5397 errmsg = "truncated data";
5398 startinpos = ((const char *)q) - starts;
5399 endinpos = ((const char *)e) - starts;
5400 break;
5401 /* The remaining input chars are ignored if the callback
5402 chooses to skip the input */
5403 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005404 q -= 2;
5405 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005406 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005407 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005408 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005409 endinpos = ((const char *)e) - starts;
5410 break;
5411 case 2:
5412 errmsg = "illegal encoding";
5413 startinpos = ((const char *)q) - 2 - starts;
5414 endinpos = startinpos + 2;
5415 break;
5416 case 3:
5417 errmsg = "illegal UTF-16 surrogate";
5418 startinpos = ((const char *)q) - 4 - starts;
5419 endinpos = startinpos + 2;
5420 break;
5421 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005422 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005423 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005424 continue;
5425 }
5426
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005427 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005428 errors,
5429 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005430 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005431 &starts,
5432 (const char **)&e,
5433 &startinpos,
5434 &endinpos,
5435 &exc,
5436 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005437 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439 }
5440
Antoine Pitrou63065d72012-05-15 23:48:04 +02005441End:
Walter Dörwald69652032004-09-07 20:24:22 +00005442 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005444
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005445 Py_XDECREF(errorHandler);
5446 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005447 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005448
Benjamin Peterson29060642009-01-31 22:14:21 +00005449 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005450 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005451 Py_XDECREF(errorHandler);
5452 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453 return NULL;
5454}
5455
Tim Peters772747b2001-08-09 22:21:55 +00005456PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005457_PyUnicode_EncodeUTF16(PyObject *str,
5458 const char *errors,
5459 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005461 enum PyUnicode_Kind kind;
5462 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005463 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005464 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005466 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005467#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005468 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005469#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005470 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005471#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005472 const char *encoding;
5473 Py_ssize_t nsize, pos;
5474 PyObject *errorHandler = NULL;
5475 PyObject *exc = NULL;
5476 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005477
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005478 if (!PyUnicode_Check(str)) {
5479 PyErr_BadArgument();
5480 return NULL;
5481 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005482 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005483 return NULL;
5484 kind = PyUnicode_KIND(str);
5485 data = PyUnicode_DATA(str);
5486 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005487
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005488 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005489 if (kind == PyUnicode_4BYTE_KIND) {
5490 const Py_UCS4 *in = (const Py_UCS4 *)data;
5491 const Py_UCS4 *end = in + len;
5492 while (in < end)
5493 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005494 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005495 }
5496 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005497 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005498 nsize = len + pairs + (byteorder == 0);
5499 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005500 if (v == NULL)
5501 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005502
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005503 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005504 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005505 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005506 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005507 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005508 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005509 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005510
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005511 if (kind == PyUnicode_1BYTE_KIND) {
5512 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5513 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005514 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005515
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005516 if (byteorder < 0)
5517 encoding = "utf-16-le";
5518 else if (byteorder > 0)
5519 encoding = "utf-16-be";
5520 else
5521 encoding = "utf-16";
5522
5523 pos = 0;
5524 while (pos < len) {
5525 Py_ssize_t repsize, moreunits;
5526
5527 if (kind == PyUnicode_2BYTE_KIND) {
5528 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5529 &out, native_ordering);
5530 }
5531 else {
5532 assert(kind == PyUnicode_4BYTE_KIND);
5533 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5534 &out, native_ordering);
5535 }
5536 if (pos == len)
5537 break;
5538
5539 rep = unicode_encode_call_errorhandler(
5540 errors, &errorHandler,
5541 encoding, "surrogates not allowed",
5542 str, &exc, pos, pos + 1, &pos);
5543 if (!rep)
5544 goto error;
5545
5546 if (PyBytes_Check(rep)) {
5547 repsize = PyBytes_GET_SIZE(rep);
5548 if (repsize & 1) {
5549 raise_encode_exception(&exc, encoding,
5550 str, pos - 1, pos,
5551 "surrogates not allowed");
5552 goto error;
5553 }
5554 moreunits = repsize / 2;
5555 }
5556 else {
5557 assert(PyUnicode_Check(rep));
5558 if (PyUnicode_READY(rep) < 0)
5559 goto error;
5560 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5561 if (!PyUnicode_IS_ASCII(rep)) {
5562 raise_encode_exception(&exc, encoding,
5563 str, pos - 1, pos,
5564 "surrogates not allowed");
5565 goto error;
5566 }
5567 }
5568
5569 /* two bytes are reserved for each surrogate */
5570 if (moreunits > 1) {
5571 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5572 Py_ssize_t morebytes = 2 * (moreunits - 1);
5573 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5574 /* integer overflow */
5575 PyErr_NoMemory();
5576 goto error;
5577 }
5578 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5579 goto error;
5580 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5581 }
5582
5583 if (PyBytes_Check(rep)) {
5584 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5585 out += moreunits;
5586 } else /* rep is unicode */ {
5587 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5588 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5589 &out, native_ordering);
5590 }
5591
5592 Py_CLEAR(rep);
5593 }
5594
5595 /* Cut back to size actually needed. This is necessary for, for example,
5596 encoding of a string containing isolated surrogates and the 'ignore' handler
5597 is used. */
5598 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5599 if (nsize != PyBytes_GET_SIZE(v))
5600 _PyBytes_Resize(&v, nsize);
5601 Py_XDECREF(errorHandler);
5602 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005603 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005604 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005605 error:
5606 Py_XDECREF(rep);
5607 Py_XDECREF(errorHandler);
5608 Py_XDECREF(exc);
5609 Py_XDECREF(v);
5610 return NULL;
5611#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612}
5613
Alexander Belopolsky40018472011-02-26 01:02:56 +00005614PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005615PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5616 Py_ssize_t size,
5617 const char *errors,
5618 int byteorder)
5619{
5620 PyObject *result;
5621 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5622 if (tmp == NULL)
5623 return NULL;
5624 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5625 Py_DECREF(tmp);
5626 return result;
5627}
5628
5629PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005630PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005632 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633}
5634
5635/* --- Unicode Escape Codec ----------------------------------------------- */
5636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5638 if all the escapes in the string make it still a valid ASCII string.
5639 Returns -1 if any escapes were found which cause the string to
5640 pop out of ASCII range. Otherwise returns the length of the
5641 required buffer to hold the string.
5642 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005643static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005644length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5645{
5646 const unsigned char *p = (const unsigned char *)s;
5647 const unsigned char *end = p + size;
5648 Py_ssize_t length = 0;
5649
5650 if (size < 0)
5651 return -1;
5652
5653 for (; p < end; ++p) {
5654 if (*p > 127) {
5655 /* Non-ASCII */
5656 return -1;
5657 }
5658 else if (*p != '\\') {
5659 /* Normal character */
5660 ++length;
5661 }
5662 else {
5663 /* Backslash-escape, check next char */
5664 ++p;
5665 /* Escape sequence reaches till end of string or
5666 non-ASCII follow-up. */
5667 if (p >= end || *p > 127)
5668 return -1;
5669 switch (*p) {
5670 case '\n':
5671 /* backslash + \n result in zero characters */
5672 break;
5673 case '\\': case '\'': case '\"':
5674 case 'b': case 'f': case 't':
5675 case 'n': case 'r': case 'v': case 'a':
5676 ++length;
5677 break;
5678 case '0': case '1': case '2': case '3':
5679 case '4': case '5': case '6': case '7':
5680 case 'x': case 'u': case 'U': case 'N':
5681 /* these do not guarantee ASCII characters */
5682 return -1;
5683 default:
5684 /* count the backslash + the other character */
5685 length += 2;
5686 }
5687 }
5688 }
5689 return length;
5690}
5691
Fredrik Lundh06d12682001-01-24 07:59:11 +00005692static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005693
Alexander Belopolsky40018472011-02-26 01:02:56 +00005694PyObject *
5695PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005696 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005697 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005698{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005699 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005700 Py_ssize_t startinpos;
5701 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005702 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005704 char* message;
5705 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005706 PyObject *errorHandler = NULL;
5707 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005709
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005710 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005711 if (len == 0)
5712 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005713
5714 /* After length_of_escaped_ascii_string() there are two alternatives,
5715 either the string is pure ASCII with named escapes like \n, etc.
5716 and we determined it's exact size (common case)
5717 or it contains \x, \u, ... escape sequences. then we create a
5718 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005719 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005720 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005721 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005722 }
5723 else {
5724 /* Escaped strings will always be longer than the resulting
5725 Unicode string, so we start with size here and then reduce the
5726 length after conversion to the true value.
5727 (but if the error callback returns a long replacement string
5728 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005729 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005730 }
5731
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005733 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005735
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736 while (s < end) {
5737 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005738 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005739 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
5741 /* Non-escape characters are interpreted as Unicode ordinals */
5742 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005743 x = (unsigned char)*s;
5744 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005745 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005746 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747 continue;
5748 }
5749
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 /* \ - Escapes */
5752 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005753 c = *s++;
5754 if (s > end)
5755 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005757 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758
Benjamin Peterson29060642009-01-31 22:14:21 +00005759 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005760#define WRITECHAR(ch) \
5761 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005762 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005763 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005764 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005765
Guido van Rossumd57fd912000-03-10 22:53:23 +00005766 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005767 case '\\': WRITECHAR('\\'); break;
5768 case '\'': WRITECHAR('\''); break;
5769 case '\"': WRITECHAR('\"'); break;
5770 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005771 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005772 case 'f': WRITECHAR('\014'); break;
5773 case 't': WRITECHAR('\t'); break;
5774 case 'n': WRITECHAR('\n'); break;
5775 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005776 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005777 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005778 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005779 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780
Benjamin Peterson29060642009-01-31 22:14:21 +00005781 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 case '0': case '1': case '2': case '3':
5783 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005784 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005785 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005786 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005787 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005788 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005789 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005790 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005791 break;
5792
Benjamin Peterson29060642009-01-31 22:14:21 +00005793 /* hex escapes */
5794 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005795 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005796 digits = 2;
5797 message = "truncated \\xXX escape";
5798 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005801 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005802 digits = 4;
5803 message = "truncated \\uXXXX escape";
5804 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005805
Benjamin Peterson29060642009-01-31 22:14:21 +00005806 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005807 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005808 digits = 8;
5809 message = "truncated \\UXXXXXXXX escape";
5810 hexescape:
5811 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005812 if (end - s < digits) {
5813 /* count only hex digits */
5814 for (; s < end; ++s) {
5815 c = (unsigned char)*s;
5816 if (!Py_ISXDIGIT(c))
5817 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005818 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005819 goto error;
5820 }
5821 for (; digits--; ++s) {
5822 c = (unsigned char)*s;
5823 if (!Py_ISXDIGIT(c))
5824 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005825 chr = (chr<<4) & ~0xF;
5826 if (c >= '0' && c <= '9')
5827 chr += c - '0';
5828 else if (c >= 'a' && c <= 'f')
5829 chr += 10 + c - 'a';
5830 else
5831 chr += 10 + c - 'A';
5832 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005833 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 /* _decoding_error will have already written into the
5835 target buffer. */
5836 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005838 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005839 message = "illegal Unicode character";
5840 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005841 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005842 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 break;
5844
Benjamin Peterson29060642009-01-31 22:14:21 +00005845 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005846 case 'N':
5847 message = "malformed \\N character escape";
5848 if (ucnhash_CAPI == NULL) {
5849 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5851 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005852 if (ucnhash_CAPI == NULL)
5853 goto ucnhashError;
5854 }
5855 if (*s == '{') {
5856 const char *start = s+1;
5857 /* look for the closing brace */
5858 while (*s != '}' && s < end)
5859 s++;
5860 if (s > start && s < end && *s == '}') {
5861 /* found a name. look it up in the unicode database */
5862 message = "unknown Unicode character name";
5863 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005864 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005865 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005866 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005867 goto store;
5868 }
5869 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005870 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005871
5872 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005873 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874 message = "\\ at end of string";
5875 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005876 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005877 }
5878 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005879 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005880 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005881 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005882 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005884 continue;
5885
5886 error:
5887 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005888 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005889 errors, &errorHandler,
5890 "unicodeescape", message,
5891 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005892 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005893 goto onError;
5894 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005896#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005897
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005898 Py_XDECREF(errorHandler);
5899 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005900 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005901
Benjamin Peterson29060642009-01-31 22:14:21 +00005902 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005903 PyErr_SetString(
5904 PyExc_UnicodeError,
5905 "\\N escapes not supported (can't load unicodedata module)"
5906 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005907 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005908 Py_XDECREF(errorHandler);
5909 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005910 return NULL;
5911
Benjamin Peterson29060642009-01-31 22:14:21 +00005912 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005913 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005914 Py_XDECREF(errorHandler);
5915 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 return NULL;
5917}
5918
5919/* Return a Unicode-Escape string version of the Unicode object.
5920
5921 If quotes is true, the string is enclosed in u"" or u'' quotes as
5922 appropriate.
5923
5924*/
5925
Alexander Belopolsky40018472011-02-26 01:02:56 +00005926PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005927PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005929 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005930 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005932 int kind;
5933 void *data;
5934 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935
Ezio Melottie7f90372012-10-05 03:33:31 +03005936 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005937 escape.
5938
Ezio Melottie7f90372012-10-05 03:33:31 +03005939 For UCS1 strings it's '\xxx', 4 bytes per source character.
5940 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5941 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005942 */
5943
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005944 if (!PyUnicode_Check(unicode)) {
5945 PyErr_BadArgument();
5946 return NULL;
5947 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005948 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005949 return NULL;
5950 len = PyUnicode_GET_LENGTH(unicode);
5951 kind = PyUnicode_KIND(unicode);
5952 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005953 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005954 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5955 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5956 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5957 }
5958
5959 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005960 return PyBytes_FromStringAndSize(NULL, 0);
5961
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005962 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005963 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005964
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005965 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005966 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005967 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 if (repr == NULL)
5970 return NULL;
5971
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005972 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005974 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005975 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005976
Walter Dörwald79e913e2007-05-12 11:08:06 +00005977 /* Escape backslashes */
5978 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979 *p++ = '\\';
5980 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005981 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005982 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005983
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005984 /* Map 21-bit characters to '\U00xxxxxx' */
5985 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005986 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005987 *p++ = '\\';
5988 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005989 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5993 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5994 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5995 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5996 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005997 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005998 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005999
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006001 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 *p++ = '\\';
6003 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006004 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6005 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6006 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6007 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006009
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006010 /* Map special whitespace to '\t', \n', '\r' */
6011 else if (ch == '\t') {
6012 *p++ = '\\';
6013 *p++ = 't';
6014 }
6015 else if (ch == '\n') {
6016 *p++ = '\\';
6017 *p++ = 'n';
6018 }
6019 else if (ch == '\r') {
6020 *p++ = '\\';
6021 *p++ = 'r';
6022 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006023
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006024 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006025 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006027 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006028 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6029 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006030 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006031
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032 /* Copy everything else as-is */
6033 else
6034 *p++ = (char) ch;
6035 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006037 assert(p - PyBytes_AS_STRING(repr) > 0);
6038 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6039 return NULL;
6040 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041}
6042
Alexander Belopolsky40018472011-02-26 01:02:56 +00006043PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6045 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006047 PyObject *result;
6048 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6049 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006051 result = PyUnicode_AsUnicodeEscapeString(tmp);
6052 Py_DECREF(tmp);
6053 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054}
6055
6056/* --- Raw Unicode Escape Codec ------------------------------------------- */
6057
Alexander Belopolsky40018472011-02-26 01:02:56 +00006058PyObject *
6059PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006060 Py_ssize_t size,
6061 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006063 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006064 Py_ssize_t startinpos;
6065 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006066 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 const char *end;
6068 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006069 PyObject *errorHandler = NULL;
6070 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006071
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006072 if (size == 0)
6073 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006074
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 /* Escaped strings will always be longer than the resulting
6076 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006077 length after conversion to the true value. (But decoding error
6078 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006079 _PyUnicodeWriter_Init(&writer);
6080 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006081
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082 end = s + size;
6083 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 unsigned char c;
6085 Py_UCS4 x;
6086 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006087 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 /* Non-escape characters are interpreted as Unicode ordinals */
6090 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006091 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006092 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006093 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006094 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006095 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006096 startinpos = s-starts;
6097
6098 /* \u-escapes are only interpreted iff the number of leading
6099 backslashes if odd */
6100 bs = s;
6101 for (;s < end;) {
6102 if (*s != '\\')
6103 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006105 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006106 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 }
6108 if (((s - bs) & 1) == 0 ||
6109 s >= end ||
6110 (*s != 'u' && *s != 'U')) {
6111 continue;
6112 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006113 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 count = *s=='u' ? 4 : 8;
6115 s++;
6116
6117 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 for (x = 0, i = 0; i < count; ++i, ++s) {
6119 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006120 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006121 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006122 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006123 errors, &errorHandler,
6124 "rawunicodeescape", "truncated \\uXXXX",
6125 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006126 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 goto onError;
6128 goto nextByte;
6129 }
6130 x = (x<<4) & ~0xF;
6131 if (c >= '0' && c <= '9')
6132 x += c - '0';
6133 else if (c >= 'a' && c <= 'f')
6134 x += 10 + c - 'a';
6135 else
6136 x += 10 + c - 'A';
6137 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006138 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006139 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006140 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006141 }
6142 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006143 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006144 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006145 errors, &errorHandler,
6146 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006147 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006148 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006150 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 nextByte:
6152 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006153 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006154 Py_XDECREF(errorHandler);
6155 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006156 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006157
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006159 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006160 Py_XDECREF(errorHandler);
6161 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162 return NULL;
6163}
6164
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165
Alexander Belopolsky40018472011-02-26 01:02:56 +00006166PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006168{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006169 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006170 char *p;
6171 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006172 Py_ssize_t expandsize, pos;
6173 int kind;
6174 void *data;
6175 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006176
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177 if (!PyUnicode_Check(unicode)) {
6178 PyErr_BadArgument();
6179 return NULL;
6180 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006181 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006182 return NULL;
6183 kind = PyUnicode_KIND(unicode);
6184 data = PyUnicode_DATA(unicode);
6185 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006186 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6187 bytes, and 1 byte characters 4. */
6188 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006192
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194 if (repr == NULL)
6195 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006197 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006199 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 for (pos = 0; pos < len; pos++) {
6201 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006202 /* Map 32-bit characters to '\Uxxxxxxxx' */
6203 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006204 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006205 *p++ = '\\';
6206 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006207 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6208 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6209 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6210 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6211 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6212 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6213 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6214 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006215 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006216 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006217 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006218 *p++ = '\\';
6219 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006220 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6221 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6222 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6223 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006225 /* Copy everything else as-is */
6226 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 *p++ = (char) ch;
6228 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006229
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006230 assert(p > q);
6231 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006232 return NULL;
6233 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234}
6235
Alexander Belopolsky40018472011-02-26 01:02:56 +00006236PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6238 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240 PyObject *result;
6241 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6242 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006243 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006244 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6245 Py_DECREF(tmp);
6246 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006247}
6248
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006249/* --- Unicode Internal Codec ------------------------------------------- */
6250
Alexander Belopolsky40018472011-02-26 01:02:56 +00006251PyObject *
6252_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006253 Py_ssize_t size,
6254 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006255{
6256 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006257 Py_ssize_t startinpos;
6258 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006259 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260 const char *end;
6261 const char *reason;
6262 PyObject *errorHandler = NULL;
6263 PyObject *exc = NULL;
6264
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006265 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006266 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006267 1))
6268 return NULL;
6269
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006270 if (size == 0)
6271 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006272
Victor Stinner8f674cc2013-04-17 23:02:17 +02006273 _PyUnicodeWriter_Init(&writer);
6274 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6275 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006277 }
6278 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279
Victor Stinner8f674cc2013-04-17 23:02:17 +02006280 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006281 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006282 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006283 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006284 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006285 endinpos = end-starts;
6286 reason = "truncated input";
6287 goto error;
6288 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006289 /* We copy the raw representation one byte at a time because the
6290 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006291 ((char *) &uch)[0] = s[0];
6292 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006293#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006294 ((char *) &uch)[2] = s[2];
6295 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006296#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006297 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006298#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299 /* We have to sanity check the raw data, otherwise doom looms for
6300 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006301 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006302 endinpos = s - starts + Py_UNICODE_SIZE;
6303 reason = "illegal code point (> 0x10FFFF)";
6304 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006305 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006306#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006307 s += Py_UNICODE_SIZE;
6308#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006309 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006310 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006311 Py_UNICODE uch2;
6312 ((char *) &uch2)[0] = s[0];
6313 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006314 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006315 {
Victor Stinner551ac952011-11-29 22:58:13 +01006316 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006317 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006318 }
6319 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006320#endif
6321
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006322 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006323 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006324 continue;
6325
6326 error:
6327 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006328 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006329 errors, &errorHandler,
6330 "unicode_internal", reason,
6331 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006332 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006333 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006334 }
6335
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336 Py_XDECREF(errorHandler);
6337 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006338 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006341 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006342 Py_XDECREF(errorHandler);
6343 Py_XDECREF(exc);
6344 return NULL;
6345}
6346
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347/* --- Latin-1 Codec ------------------------------------------------------ */
6348
Alexander Belopolsky40018472011-02-26 01:02:56 +00006349PyObject *
6350PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006351 Py_ssize_t size,
6352 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006354 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006355 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006356}
6357
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006359static void
6360make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006361 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006362 PyObject *unicode,
6363 Py_ssize_t startpos, Py_ssize_t endpos,
6364 const char *reason)
6365{
6366 if (*exceptionObject == NULL) {
6367 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006368 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006369 encoding, unicode, startpos, endpos, reason);
6370 }
6371 else {
6372 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6373 goto onError;
6374 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6375 goto onError;
6376 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6377 goto onError;
6378 return;
6379 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006380 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006381 }
6382}
6383
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006385static void
6386raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006387 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006388 PyObject *unicode,
6389 Py_ssize_t startpos, Py_ssize_t endpos,
6390 const char *reason)
6391{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006392 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006393 encoding, unicode, startpos, endpos, reason);
6394 if (*exceptionObject != NULL)
6395 PyCodec_StrictErrors(*exceptionObject);
6396}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397
6398/* error handling callback helper:
6399 build arguments, call the callback and check the arguments,
6400 put the result into newpos and return the replacement string, which
6401 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006402static PyObject *
6403unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006404 PyObject **errorHandler,
6405 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006406 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006407 Py_ssize_t startpos, Py_ssize_t endpos,
6408 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006410 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006411 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 PyObject *restuple;
6413 PyObject *resunicode;
6414
6415 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006416 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 }
6420
Benjamin Petersonbac79492012-01-14 13:34:47 -05006421 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 return NULL;
6423 len = PyUnicode_GET_LENGTH(unicode);
6424
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006425 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006428 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429
6430 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006431 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006435 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006436 Py_DECREF(restuple);
6437 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006439 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 &resunicode, newpos)) {
6441 Py_DECREF(restuple);
6442 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006443 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006444 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6445 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6446 Py_DECREF(restuple);
6447 return NULL;
6448 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006450 *newpos = len + *newpos;
6451 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006452 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 Py_DECREF(restuple);
6454 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006455 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006456 Py_INCREF(resunicode);
6457 Py_DECREF(restuple);
6458 return resunicode;
6459}
6460
Alexander Belopolsky40018472011-02-26 01:02:56 +00006461static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006462unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006463 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006464 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006465{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 /* input state */
6467 Py_ssize_t pos=0, size;
6468 int kind;
6469 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470 /* output object */
6471 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006472 /* pointer into the output */
6473 char *str;
6474 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006475 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006476 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6477 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478 PyObject *errorHandler = NULL;
6479 PyObject *exc = NULL;
6480 /* the following variable is used for caching string comparisons
6481 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6482 int known_errorHandler = -1;
6483
Benjamin Petersonbac79492012-01-14 13:34:47 -05006484 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006485 return NULL;
6486 size = PyUnicode_GET_LENGTH(unicode);
6487 kind = PyUnicode_KIND(unicode);
6488 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006489 /* allocate enough for a simple encoding without
6490 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006491 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006492 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006493 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006494 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006495 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006496 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006497 ressize = size;
6498
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 while (pos < size) {
6500 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006501
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 /* can we encode this? */
6503 if (c<limit) {
6504 /* no overflow check, because we know that the space is enough */
6505 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006507 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 Py_ssize_t requiredsize;
6510 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006513 Py_ssize_t collstart = pos;
6514 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006516 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 ++collend;
6518 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6519 if (known_errorHandler==-1) {
6520 if ((errors==NULL) || (!strcmp(errors, "strict")))
6521 known_errorHandler = 1;
6522 else if (!strcmp(errors, "replace"))
6523 known_errorHandler = 2;
6524 else if (!strcmp(errors, "ignore"))
6525 known_errorHandler = 3;
6526 else if (!strcmp(errors, "xmlcharrefreplace"))
6527 known_errorHandler = 4;
6528 else
6529 known_errorHandler = 0;
6530 }
6531 switch (known_errorHandler) {
6532 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006533 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 goto onError;
6535 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006536 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 *str++ = '?'; /* fall through */
6538 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 break;
6541 case 4: /* xmlcharrefreplace */
6542 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006543 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006545 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006547 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006549 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006550 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006551 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006552 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006553 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006554 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006555 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006556 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006557 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006558 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006559 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006560 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006561 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006562 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006563 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006564 if (requiredsize > PY_SSIZE_T_MAX - incr)
6565 goto overflow;
6566 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006567 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006568 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6569 goto overflow;
6570 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006571 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006572 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006573 requiredsize = 2*ressize;
6574 if (_PyBytes_Resize(&res, requiredsize))
6575 goto onError;
6576 str = PyBytes_AS_STRING(res) + respos;
6577 ressize = requiredsize;
6578 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 /* generate replacement */
6580 for (i = collstart; i < collend; ++i) {
6581 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006582 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006584 break;
6585 default:
6586 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006587 encoding, reason, unicode, &exc,
6588 collstart, collend, &newpos);
6589 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006590 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006592 if (PyBytes_Check(repunicode)) {
6593 /* Directly copy bytes result to output. */
6594 repsize = PyBytes_Size(repunicode);
6595 if (repsize > 1) {
6596 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006597 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006598 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6599 Py_DECREF(repunicode);
6600 goto overflow;
6601 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006602 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6603 Py_DECREF(repunicode);
6604 goto onError;
6605 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006606 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006607 ressize += repsize-1;
6608 }
6609 memcpy(str, PyBytes_AsString(repunicode), repsize);
6610 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006612 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006613 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006614 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 /* need more space? (at least enough for what we
6616 have+the replacement+the rest of the string, so
6617 we won't have to check space for encodable characters) */
6618 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006619 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006620 requiredsize = respos;
6621 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6622 goto overflow;
6623 requiredsize += repsize;
6624 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6625 goto overflow;
6626 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006628 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 requiredsize = 2*ressize;
6630 if (_PyBytes_Resize(&res, requiredsize)) {
6631 Py_DECREF(repunicode);
6632 goto onError;
6633 }
6634 str = PyBytes_AS_STRING(res) + respos;
6635 ressize = requiredsize;
6636 }
6637 /* check if there is anything unencodable in the replacement
6638 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639 for (i = 0; repsize-->0; ++i, ++str) {
6640 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006641 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006642 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006644 Py_DECREF(repunicode);
6645 goto onError;
6646 }
6647 *str = (char)c;
6648 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006649 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006650 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006651 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006652 }
6653 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006654 /* Resize if we allocated to much */
6655 size = str - PyBytes_AS_STRING(res);
6656 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006657 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006658 if (_PyBytes_Resize(&res, size) < 0)
6659 goto onError;
6660 }
6661
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662 Py_XDECREF(errorHandler);
6663 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006664 return res;
6665
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006666 overflow:
6667 PyErr_SetString(PyExc_OverflowError,
6668 "encoded result is too long for a Python string");
6669
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006670 onError:
6671 Py_XDECREF(res);
6672 Py_XDECREF(errorHandler);
6673 Py_XDECREF(exc);
6674 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675}
6676
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006678PyObject *
6679PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006680 Py_ssize_t size,
6681 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006682{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006683 PyObject *result;
6684 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6685 if (unicode == NULL)
6686 return NULL;
6687 result = unicode_encode_ucs1(unicode, errors, 256);
6688 Py_DECREF(unicode);
6689 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006690}
6691
Alexander Belopolsky40018472011-02-26 01:02:56 +00006692PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006693_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006694{
6695 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006696 PyErr_BadArgument();
6697 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006699 if (PyUnicode_READY(unicode) == -1)
6700 return NULL;
6701 /* Fast path: if it is a one-byte string, construct
6702 bytes object directly. */
6703 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6704 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6705 PyUnicode_GET_LENGTH(unicode));
6706 /* Non-Latin-1 characters present. Defer to above function to
6707 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006709}
6710
6711PyObject*
6712PyUnicode_AsLatin1String(PyObject *unicode)
6713{
6714 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006715}
6716
6717/* --- 7-bit ASCII Codec -------------------------------------------------- */
6718
Alexander Belopolsky40018472011-02-26 01:02:56 +00006719PyObject *
6720PyUnicode_DecodeASCII(const char *s,
6721 Py_ssize_t size,
6722 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006723{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006724 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006725 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006726 int kind;
6727 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006728 Py_ssize_t startinpos;
6729 Py_ssize_t endinpos;
6730 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006731 const char *e;
6732 PyObject *errorHandler = NULL;
6733 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006734
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006736 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006737
Guido van Rossumd57fd912000-03-10 22:53:23 +00006738 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006739 if (size == 1 && (unsigned char)s[0] < 128)
6740 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006741
Victor Stinner8f674cc2013-04-17 23:02:17 +02006742 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006743 writer.min_length = size;
6744 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006745 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006746
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006747 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006748 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006749 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006750 writer.pos = outpos;
6751 if (writer.pos == size)
6752 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006753
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006754 s += writer.pos;
6755 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006756 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006757 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006759 PyUnicode_WRITE(kind, data, writer.pos, c);
6760 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006761 ++s;
6762 }
6763 else {
6764 startinpos = s-starts;
6765 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006766 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006767 errors, &errorHandler,
6768 "ascii", "ordinal not in range(128)",
6769 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006770 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006772 kind = writer.kind;
6773 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006775 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006776 Py_XDECREF(errorHandler);
6777 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006778 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006779
Benjamin Peterson29060642009-01-31 22:14:21 +00006780 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006781 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006782 Py_XDECREF(errorHandler);
6783 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784 return NULL;
6785}
6786
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006787/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006788PyObject *
6789PyUnicode_EncodeASCII(const Py_UNICODE *p,
6790 Py_ssize_t size,
6791 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006793 PyObject *result;
6794 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6795 if (unicode == NULL)
6796 return NULL;
6797 result = unicode_encode_ucs1(unicode, errors, 128);
6798 Py_DECREF(unicode);
6799 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006800}
6801
Alexander Belopolsky40018472011-02-26 01:02:56 +00006802PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006803_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006804{
6805 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006806 PyErr_BadArgument();
6807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006808 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006809 if (PyUnicode_READY(unicode) == -1)
6810 return NULL;
6811 /* Fast path: if it is an ASCII-only string, construct bytes object
6812 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006813 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006814 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6815 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006816 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006817}
6818
6819PyObject *
6820PyUnicode_AsASCIIString(PyObject *unicode)
6821{
6822 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006823}
6824
Victor Stinner99b95382011-07-04 14:23:54 +02006825#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006826
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006827/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006828
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006829#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006830#define NEED_RETRY
6831#endif
6832
Victor Stinner3a50e702011-10-18 21:21:00 +02006833#ifndef WC_ERR_INVALID_CHARS
6834# define WC_ERR_INVALID_CHARS 0x0080
6835#endif
6836
6837static char*
6838code_page_name(UINT code_page, PyObject **obj)
6839{
6840 *obj = NULL;
6841 if (code_page == CP_ACP)
6842 return "mbcs";
6843 if (code_page == CP_UTF7)
6844 return "CP_UTF7";
6845 if (code_page == CP_UTF8)
6846 return "CP_UTF8";
6847
6848 *obj = PyBytes_FromFormat("cp%u", code_page);
6849 if (*obj == NULL)
6850 return NULL;
6851 return PyBytes_AS_STRING(*obj);
6852}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006853
Alexander Belopolsky40018472011-02-26 01:02:56 +00006854static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006855is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006856{
6857 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006859
Victor Stinner3a50e702011-10-18 21:21:00 +02006860 if (!IsDBCSLeadByteEx(code_page, *curr))
6861 return 0;
6862
6863 prev = CharPrevExA(code_page, s, curr, 0);
6864 if (prev == curr)
6865 return 1;
6866 /* FIXME: This code is limited to "true" double-byte encodings,
6867 as it assumes an incomplete character consists of a single
6868 byte. */
6869 if (curr - prev == 2)
6870 return 1;
6871 if (!IsDBCSLeadByteEx(code_page, *prev))
6872 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006873 return 0;
6874}
6875
Victor Stinner3a50e702011-10-18 21:21:00 +02006876static DWORD
6877decode_code_page_flags(UINT code_page)
6878{
6879 if (code_page == CP_UTF7) {
6880 /* The CP_UTF7 decoder only supports flags=0 */
6881 return 0;
6882 }
6883 else
6884 return MB_ERR_INVALID_CHARS;
6885}
6886
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006887/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006888 * Decode a byte string from a Windows code page into unicode object in strict
6889 * mode.
6890 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006891 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6892 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006893 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006894static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006895decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006896 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006897 const char *in,
6898 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899{
Victor Stinner3a50e702011-10-18 21:21:00 +02006900 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006901 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006903
6904 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006905 assert(insize > 0);
6906 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6907 if (outsize <= 0)
6908 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909
6910 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006911 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006912 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006913 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006914 if (*v == NULL)
6915 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006916 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006917 }
6918 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006920 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006921 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006922 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006923 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006924 }
6925
6926 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006927 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6928 if (outsize <= 0)
6929 goto error;
6930 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006931
Victor Stinner3a50e702011-10-18 21:21:00 +02006932error:
6933 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6934 return -2;
6935 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006936 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006937}
6938
Victor Stinner3a50e702011-10-18 21:21:00 +02006939/*
6940 * Decode a byte string from a code page into unicode object with an error
6941 * handler.
6942 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006943 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006944 * UnicodeDecodeError exception and returns -1 on error.
6945 */
6946static int
6947decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006948 PyObject **v,
6949 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006950 const char *errors)
6951{
6952 const char *startin = in;
6953 const char *endin = in + size;
6954 const DWORD flags = decode_code_page_flags(code_page);
6955 /* Ideally, we should get reason from FormatMessage. This is the Windows
6956 2000 English version of the message. */
6957 const char *reason = "No mapping for the Unicode character exists "
6958 "in the target code page.";
6959 /* each step cannot decode more than 1 character, but a character can be
6960 represented as a surrogate pair */
6961 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006962 int insize;
6963 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006964 PyObject *errorHandler = NULL;
6965 PyObject *exc = NULL;
6966 PyObject *encoding_obj = NULL;
6967 char *encoding;
6968 DWORD err;
6969 int ret = -1;
6970
6971 assert(size > 0);
6972
6973 encoding = code_page_name(code_page, &encoding_obj);
6974 if (encoding == NULL)
6975 return -1;
6976
6977 if (errors == NULL || strcmp(errors, "strict") == 0) {
6978 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6979 UnicodeDecodeError. */
6980 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6981 if (exc != NULL) {
6982 PyCodec_StrictErrors(exc);
6983 Py_CLEAR(exc);
6984 }
6985 goto error;
6986 }
6987
6988 if (*v == NULL) {
6989 /* Create unicode object */
6990 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6991 PyErr_NoMemory();
6992 goto error;
6993 }
Victor Stinnerab595942011-12-17 04:59:06 +01006994 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006995 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006996 if (*v == NULL)
6997 goto error;
6998 startout = PyUnicode_AS_UNICODE(*v);
6999 }
7000 else {
7001 /* Extend unicode object */
7002 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7003 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7004 PyErr_NoMemory();
7005 goto error;
7006 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007007 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007008 goto error;
7009 startout = PyUnicode_AS_UNICODE(*v) + n;
7010 }
7011
7012 /* Decode the byte string character per character */
7013 out = startout;
7014 while (in < endin)
7015 {
7016 /* Decode a character */
7017 insize = 1;
7018 do
7019 {
7020 outsize = MultiByteToWideChar(code_page, flags,
7021 in, insize,
7022 buffer, Py_ARRAY_LENGTH(buffer));
7023 if (outsize > 0)
7024 break;
7025 err = GetLastError();
7026 if (err != ERROR_NO_UNICODE_TRANSLATION
7027 && err != ERROR_INSUFFICIENT_BUFFER)
7028 {
7029 PyErr_SetFromWindowsErr(0);
7030 goto error;
7031 }
7032 insize++;
7033 }
7034 /* 4=maximum length of a UTF-8 sequence */
7035 while (insize <= 4 && (in + insize) <= endin);
7036
7037 if (outsize <= 0) {
7038 Py_ssize_t startinpos, endinpos, outpos;
7039
7040 startinpos = in - startin;
7041 endinpos = startinpos + 1;
7042 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007043 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007044 errors, &errorHandler,
7045 encoding, reason,
7046 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007047 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007048 {
7049 goto error;
7050 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007051 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007052 }
7053 else {
7054 in += insize;
7055 memcpy(out, buffer, outsize * sizeof(wchar_t));
7056 out += outsize;
7057 }
7058 }
7059
7060 /* write a NUL character at the end */
7061 *out = 0;
7062
7063 /* Extend unicode object */
7064 outsize = out - startout;
7065 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007066 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007067 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007069
7070error:
7071 Py_XDECREF(encoding_obj);
7072 Py_XDECREF(errorHandler);
7073 Py_XDECREF(exc);
7074 return ret;
7075}
7076
Victor Stinner3a50e702011-10-18 21:21:00 +02007077static PyObject *
7078decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007079 const char *s, Py_ssize_t size,
7080 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081{
Victor Stinner76a31a62011-11-04 00:05:13 +01007082 PyObject *v = NULL;
7083 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084
Victor Stinner3a50e702011-10-18 21:21:00 +02007085 if (code_page < 0) {
7086 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7087 return NULL;
7088 }
7089
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092
Victor Stinner76a31a62011-11-04 00:05:13 +01007093 do
7094 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007096 if (size > INT_MAX) {
7097 chunk_size = INT_MAX;
7098 final = 0;
7099 done = 0;
7100 }
7101 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007103 {
7104 chunk_size = (int)size;
7105 final = (consumed == NULL);
7106 done = 1;
7107 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108
Victor Stinner76a31a62011-11-04 00:05:13 +01007109 /* Skip trailing lead-byte unless 'final' is set */
7110 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7111 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112
Victor Stinner76a31a62011-11-04 00:05:13 +01007113 if (chunk_size == 0 && done) {
7114 if (v != NULL)
7115 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007116 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007117 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118
Victor Stinner76a31a62011-11-04 00:05:13 +01007119
7120 converted = decode_code_page_strict(code_page, &v,
7121 s, chunk_size);
7122 if (converted == -2)
7123 converted = decode_code_page_errors(code_page, &v,
7124 s, chunk_size,
7125 errors);
7126 assert(converted != 0);
7127
7128 if (converted < 0) {
7129 Py_XDECREF(v);
7130 return NULL;
7131 }
7132
7133 if (consumed)
7134 *consumed += converted;
7135
7136 s += converted;
7137 size -= converted;
7138 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007139
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007140 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007141}
7142
Alexander Belopolsky40018472011-02-26 01:02:56 +00007143PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007144PyUnicode_DecodeCodePageStateful(int code_page,
7145 const char *s,
7146 Py_ssize_t size,
7147 const char *errors,
7148 Py_ssize_t *consumed)
7149{
7150 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7151}
7152
7153PyObject *
7154PyUnicode_DecodeMBCSStateful(const char *s,
7155 Py_ssize_t size,
7156 const char *errors,
7157 Py_ssize_t *consumed)
7158{
7159 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7160}
7161
7162PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007163PyUnicode_DecodeMBCS(const char *s,
7164 Py_ssize_t size,
7165 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007166{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007167 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7168}
7169
Victor Stinner3a50e702011-10-18 21:21:00 +02007170static DWORD
7171encode_code_page_flags(UINT code_page, const char *errors)
7172{
7173 if (code_page == CP_UTF8) {
7174 if (winver.dwMajorVersion >= 6)
7175 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7176 and later */
7177 return WC_ERR_INVALID_CHARS;
7178 else
7179 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7180 return 0;
7181 }
7182 else if (code_page == CP_UTF7) {
7183 /* CP_UTF7 only supports flags=0 */
7184 return 0;
7185 }
7186 else {
7187 if (errors != NULL && strcmp(errors, "replace") == 0)
7188 return 0;
7189 else
7190 return WC_NO_BEST_FIT_CHARS;
7191 }
7192}
7193
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007194/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 * Encode a Unicode string to a Windows code page into a byte string in strict
7196 * mode.
7197 *
7198 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007199 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007200 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007201static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007202encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007203 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007205{
Victor Stinner554f3f02010-06-16 23:33:54 +00007206 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 BOOL *pusedDefaultChar = &usedDefaultChar;
7208 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007209 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007210 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007211 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007212 const DWORD flags = encode_code_page_flags(code_page, NULL);
7213 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007214 /* Create a substring so that we can get the UTF-16 representation
7215 of just the slice under consideration. */
7216 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007217
Martin v. Löwis3d325192011-11-04 18:23:06 +01007218 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007219
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007221 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007223 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007224
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 substring = PyUnicode_Substring(unicode, offset, offset+len);
7226 if (substring == NULL)
7227 return -1;
7228 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7229 if (p == NULL) {
7230 Py_DECREF(substring);
7231 return -1;
7232 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007233 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007234
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007235 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007237 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 NULL, 0,
7239 NULL, pusedDefaultChar);
7240 if (outsize <= 0)
7241 goto error;
7242 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007243 if (pusedDefaultChar && *pusedDefaultChar) {
7244 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007246 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007249 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 if (*outbytes == NULL) {
7252 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007253 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007254 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007256 }
7257 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007258 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 const Py_ssize_t n = PyBytes_Size(*outbytes);
7260 if (outsize > PY_SSIZE_T_MAX - n) {
7261 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007262 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007263 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007265 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7266 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007267 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007268 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007269 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007270 }
7271
7272 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007274 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 out, outsize,
7276 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007277 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 if (outsize <= 0)
7279 goto error;
7280 if (pusedDefaultChar && *pusedDefaultChar)
7281 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007283
Victor Stinner3a50e702011-10-18 21:21:00 +02007284error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007285 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7287 return -2;
7288 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007289 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007290}
7291
Victor Stinner3a50e702011-10-18 21:21:00 +02007292/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007293 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007294 * error handler.
7295 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007296 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007297 * -1 on other error.
7298 */
7299static int
7300encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007301 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007302 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007303{
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007305 Py_ssize_t pos = unicode_offset;
7306 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 /* Ideally, we should get reason from FormatMessage. This is the Windows
7308 2000 English version of the message. */
7309 const char *reason = "invalid character";
7310 /* 4=maximum length of a UTF-8 sequence */
7311 char buffer[4];
7312 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7313 Py_ssize_t outsize;
7314 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 PyObject *errorHandler = NULL;
7316 PyObject *exc = NULL;
7317 PyObject *encoding_obj = NULL;
7318 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007319 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007320 PyObject *rep;
7321 int ret = -1;
7322
7323 assert(insize > 0);
7324
7325 encoding = code_page_name(code_page, &encoding_obj);
7326 if (encoding == NULL)
7327 return -1;
7328
7329 if (errors == NULL || strcmp(errors, "strict") == 0) {
7330 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7331 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007332 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 if (exc != NULL) {
7334 PyCodec_StrictErrors(exc);
7335 Py_DECREF(exc);
7336 }
7337 Py_XDECREF(encoding_obj);
7338 return -1;
7339 }
7340
7341 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7342 pusedDefaultChar = &usedDefaultChar;
7343 else
7344 pusedDefaultChar = NULL;
7345
7346 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7347 PyErr_NoMemory();
7348 goto error;
7349 }
7350 outsize = insize * Py_ARRAY_LENGTH(buffer);
7351
7352 if (*outbytes == NULL) {
7353 /* Create string object */
7354 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7355 if (*outbytes == NULL)
7356 goto error;
7357 out = PyBytes_AS_STRING(*outbytes);
7358 }
7359 else {
7360 /* Extend string object */
7361 Py_ssize_t n = PyBytes_Size(*outbytes);
7362 if (n > PY_SSIZE_T_MAX - outsize) {
7363 PyErr_NoMemory();
7364 goto error;
7365 }
7366 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7367 goto error;
7368 out = PyBytes_AS_STRING(*outbytes) + n;
7369 }
7370
7371 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007372 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007374 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7375 wchar_t chars[2];
7376 int charsize;
7377 if (ch < 0x10000) {
7378 chars[0] = (wchar_t)ch;
7379 charsize = 1;
7380 }
7381 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007382 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7383 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 charsize = 2;
7385 }
7386
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007388 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 buffer, Py_ARRAY_LENGTH(buffer),
7390 NULL, pusedDefaultChar);
7391 if (outsize > 0) {
7392 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7393 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007394 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 memcpy(out, buffer, outsize);
7396 out += outsize;
7397 continue;
7398 }
7399 }
7400 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7401 PyErr_SetFromWindowsErr(0);
7402 goto error;
7403 }
7404
Victor Stinner3a50e702011-10-18 21:21:00 +02007405 rep = unicode_encode_call_errorhandler(
7406 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007407 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007408 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 if (rep == NULL)
7410 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007411 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007412
7413 if (PyBytes_Check(rep)) {
7414 outsize = PyBytes_GET_SIZE(rep);
7415 if (outsize != 1) {
7416 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7417 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7418 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7419 Py_DECREF(rep);
7420 goto error;
7421 }
7422 out = PyBytes_AS_STRING(*outbytes) + offset;
7423 }
7424 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7425 out += outsize;
7426 }
7427 else {
7428 Py_ssize_t i;
7429 enum PyUnicode_Kind kind;
7430 void *data;
7431
Benjamin Petersonbac79492012-01-14 13:34:47 -05007432 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 Py_DECREF(rep);
7434 goto error;
7435 }
7436
7437 outsize = PyUnicode_GET_LENGTH(rep);
7438 if (outsize != 1) {
7439 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7440 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7441 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7442 Py_DECREF(rep);
7443 goto error;
7444 }
7445 out = PyBytes_AS_STRING(*outbytes) + offset;
7446 }
7447 kind = PyUnicode_KIND(rep);
7448 data = PyUnicode_DATA(rep);
7449 for (i=0; i < outsize; i++) {
7450 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7451 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007452 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007453 encoding, unicode,
7454 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 "unable to encode error handler result to ASCII");
7456 Py_DECREF(rep);
7457 goto error;
7458 }
7459 *out = (unsigned char)ch;
7460 out++;
7461 }
7462 }
7463 Py_DECREF(rep);
7464 }
7465 /* write a NUL byte */
7466 *out = 0;
7467 outsize = out - PyBytes_AS_STRING(*outbytes);
7468 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7469 if (_PyBytes_Resize(outbytes, outsize) < 0)
7470 goto error;
7471 ret = 0;
7472
7473error:
7474 Py_XDECREF(encoding_obj);
7475 Py_XDECREF(errorHandler);
7476 Py_XDECREF(exc);
7477 return ret;
7478}
7479
Victor Stinner3a50e702011-10-18 21:21:00 +02007480static PyObject *
7481encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007482 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007483 const char *errors)
7484{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007485 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007487 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007488 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007489
Benjamin Petersonbac79492012-01-14 13:34:47 -05007490 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007491 return NULL;
7492 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007493
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 if (code_page < 0) {
7495 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7496 return NULL;
7497 }
7498
Martin v. Löwis3d325192011-11-04 18:23:06 +01007499 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007500 return PyBytes_FromStringAndSize(NULL, 0);
7501
Victor Stinner7581cef2011-11-03 22:32:33 +01007502 offset = 0;
7503 do
7504 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007505#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007506 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007507 chunks. */
7508 if (len > INT_MAX/2) {
7509 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007510 done = 0;
7511 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007512 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007513#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007514 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007515 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 done = 1;
7517 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007518
Victor Stinner76a31a62011-11-04 00:05:13 +01007519 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007520 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007521 errors);
7522 if (ret == -2)
7523 ret = encode_code_page_errors(code_page, &outbytes,
7524 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007525 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007526 if (ret < 0) {
7527 Py_XDECREF(outbytes);
7528 return NULL;
7529 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007530
Victor Stinner7581cef2011-11-03 22:32:33 +01007531 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007532 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007533 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007534
Victor Stinner3a50e702011-10-18 21:21:00 +02007535 return outbytes;
7536}
7537
7538PyObject *
7539PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7540 Py_ssize_t size,
7541 const char *errors)
7542{
Victor Stinner7581cef2011-11-03 22:32:33 +01007543 PyObject *unicode, *res;
7544 unicode = PyUnicode_FromUnicode(p, size);
7545 if (unicode == NULL)
7546 return NULL;
7547 res = encode_code_page(CP_ACP, unicode, errors);
7548 Py_DECREF(unicode);
7549 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007550}
7551
7552PyObject *
7553PyUnicode_EncodeCodePage(int code_page,
7554 PyObject *unicode,
7555 const char *errors)
7556{
Victor Stinner7581cef2011-11-03 22:32:33 +01007557 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007558}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007559
Alexander Belopolsky40018472011-02-26 01:02:56 +00007560PyObject *
7561PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007562{
7563 if (!PyUnicode_Check(unicode)) {
7564 PyErr_BadArgument();
7565 return NULL;
7566 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007567 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007568}
7569
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007570#undef NEED_RETRY
7571
Victor Stinner99b95382011-07-04 14:23:54 +02007572#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007573
Guido van Rossumd57fd912000-03-10 22:53:23 +00007574/* --- Character Mapping Codec -------------------------------------------- */
7575
Victor Stinnerfb161b12013-04-18 01:44:27 +02007576static int
7577charmap_decode_string(const char *s,
7578 Py_ssize_t size,
7579 PyObject *mapping,
7580 const char *errors,
7581 _PyUnicodeWriter *writer)
7582{
7583 const char *starts = s;
7584 const char *e;
7585 Py_ssize_t startinpos, endinpos;
7586 PyObject *errorHandler = NULL, *exc = NULL;
7587 Py_ssize_t maplen;
7588 enum PyUnicode_Kind mapkind;
7589 void *mapdata;
7590 Py_UCS4 x;
7591 unsigned char ch;
7592
7593 if (PyUnicode_READY(mapping) == -1)
7594 return -1;
7595
7596 maplen = PyUnicode_GET_LENGTH(mapping);
7597 mapdata = PyUnicode_DATA(mapping);
7598 mapkind = PyUnicode_KIND(mapping);
7599
7600 e = s + size;
7601
7602 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7603 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7604 * is disabled in encoding aliases, latin1 is preferred because
7605 * its implementation is faster. */
7606 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7607 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7608 Py_UCS4 maxchar = writer->maxchar;
7609
7610 assert (writer->kind == PyUnicode_1BYTE_KIND);
7611 while (s < e) {
7612 ch = *s;
7613 x = mapdata_ucs1[ch];
7614 if (x > maxchar) {
7615 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7616 goto onError;
7617 maxchar = writer->maxchar;
7618 outdata = (Py_UCS1 *)writer->data;
7619 }
7620 outdata[writer->pos] = x;
7621 writer->pos++;
7622 ++s;
7623 }
7624 return 0;
7625 }
7626
7627 while (s < e) {
7628 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7629 enum PyUnicode_Kind outkind = writer->kind;
7630 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7631 if (outkind == PyUnicode_1BYTE_KIND) {
7632 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7633 Py_UCS4 maxchar = writer->maxchar;
7634 while (s < e) {
7635 ch = *s;
7636 x = mapdata_ucs2[ch];
7637 if (x > maxchar)
7638 goto Error;
7639 outdata[writer->pos] = x;
7640 writer->pos++;
7641 ++s;
7642 }
7643 break;
7644 }
7645 else if (outkind == PyUnicode_2BYTE_KIND) {
7646 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7647 while (s < e) {
7648 ch = *s;
7649 x = mapdata_ucs2[ch];
7650 if (x == 0xFFFE)
7651 goto Error;
7652 outdata[writer->pos] = x;
7653 writer->pos++;
7654 ++s;
7655 }
7656 break;
7657 }
7658 }
7659 ch = *s;
7660
7661 if (ch < maplen)
7662 x = PyUnicode_READ(mapkind, mapdata, ch);
7663 else
7664 x = 0xfffe; /* invalid value */
7665Error:
7666 if (x == 0xfffe)
7667 {
7668 /* undefined mapping */
7669 startinpos = s-starts;
7670 endinpos = startinpos+1;
7671 if (unicode_decode_call_errorhandler_writer(
7672 errors, &errorHandler,
7673 "charmap", "character maps to <undefined>",
7674 &starts, &e, &startinpos, &endinpos, &exc, &s,
7675 writer)) {
7676 goto onError;
7677 }
7678 continue;
7679 }
7680
7681 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7682 goto onError;
7683 ++s;
7684 }
7685 Py_XDECREF(errorHandler);
7686 Py_XDECREF(exc);
7687 return 0;
7688
7689onError:
7690 Py_XDECREF(errorHandler);
7691 Py_XDECREF(exc);
7692 return -1;
7693}
7694
7695static int
7696charmap_decode_mapping(const char *s,
7697 Py_ssize_t size,
7698 PyObject *mapping,
7699 const char *errors,
7700 _PyUnicodeWriter *writer)
7701{
7702 const char *starts = s;
7703 const char *e;
7704 Py_ssize_t startinpos, endinpos;
7705 PyObject *errorHandler = NULL, *exc = NULL;
7706 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007707 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007708
7709 e = s + size;
7710
7711 while (s < e) {
7712 ch = *s;
7713
7714 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7715 key = PyLong_FromLong((long)ch);
7716 if (key == NULL)
7717 goto onError;
7718
7719 item = PyObject_GetItem(mapping, key);
7720 Py_DECREF(key);
7721 if (item == NULL) {
7722 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7723 /* No mapping found means: mapping is undefined. */
7724 PyErr_Clear();
7725 goto Undefined;
7726 } else
7727 goto onError;
7728 }
7729
7730 /* Apply mapping */
7731 if (item == Py_None)
7732 goto Undefined;
7733 if (PyLong_Check(item)) {
7734 long value = PyLong_AS_LONG(item);
7735 if (value == 0xFFFE)
7736 goto Undefined;
7737 if (value < 0 || value > MAX_UNICODE) {
7738 PyErr_Format(PyExc_TypeError,
7739 "character mapping must be in range(0x%lx)",
7740 (unsigned long)MAX_UNICODE + 1);
7741 goto onError;
7742 }
7743
7744 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7745 goto onError;
7746 }
7747 else if (PyUnicode_Check(item)) {
7748 if (PyUnicode_READY(item) == -1)
7749 goto onError;
7750 if (PyUnicode_GET_LENGTH(item) == 1) {
7751 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7752 if (value == 0xFFFE)
7753 goto Undefined;
7754 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7755 goto onError;
7756 }
7757 else {
7758 writer->overallocate = 1;
7759 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7760 goto onError;
7761 }
7762 }
7763 else {
7764 /* wrong return value */
7765 PyErr_SetString(PyExc_TypeError,
7766 "character mapping must return integer, None or str");
7767 goto onError;
7768 }
7769 Py_CLEAR(item);
7770 ++s;
7771 continue;
7772
7773Undefined:
7774 /* undefined mapping */
7775 Py_CLEAR(item);
7776 startinpos = s-starts;
7777 endinpos = startinpos+1;
7778 if (unicode_decode_call_errorhandler_writer(
7779 errors, &errorHandler,
7780 "charmap", "character maps to <undefined>",
7781 &starts, &e, &startinpos, &endinpos, &exc, &s,
7782 writer)) {
7783 goto onError;
7784 }
7785 }
7786 Py_XDECREF(errorHandler);
7787 Py_XDECREF(exc);
7788 return 0;
7789
7790onError:
7791 Py_XDECREF(item);
7792 Py_XDECREF(errorHandler);
7793 Py_XDECREF(exc);
7794 return -1;
7795}
7796
Alexander Belopolsky40018472011-02-26 01:02:56 +00007797PyObject *
7798PyUnicode_DecodeCharmap(const char *s,
7799 Py_ssize_t size,
7800 PyObject *mapping,
7801 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007802{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007803 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007804
Guido van Rossumd57fd912000-03-10 22:53:23 +00007805 /* Default to Latin-1 */
7806 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007808
Guido van Rossumd57fd912000-03-10 22:53:23 +00007809 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007810 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007811 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007812 writer.min_length = size;
7813 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007814 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007815
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007816 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007817 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7818 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007819 }
7820 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007821 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7822 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007823 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007824 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007825
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007827 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007828 return NULL;
7829}
7830
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007831/* Charmap encoding: the lookup table */
7832
Alexander Belopolsky40018472011-02-26 01:02:56 +00007833struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007834 PyObject_HEAD
7835 unsigned char level1[32];
7836 int count2, count3;
7837 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838};
7839
7840static PyObject*
7841encoding_map_size(PyObject *obj, PyObject* args)
7842{
7843 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007844 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007846}
7847
7848static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007849 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 PyDoc_STR("Return the size (in bytes) of this object") },
7851 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852};
7853
7854static void
7855encoding_map_dealloc(PyObject* o)
7856{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007857 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858}
7859
7860static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007861 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 "EncodingMap", /*tp_name*/
7863 sizeof(struct encoding_map), /*tp_basicsize*/
7864 0, /*tp_itemsize*/
7865 /* methods */
7866 encoding_map_dealloc, /*tp_dealloc*/
7867 0, /*tp_print*/
7868 0, /*tp_getattr*/
7869 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007870 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 0, /*tp_repr*/
7872 0, /*tp_as_number*/
7873 0, /*tp_as_sequence*/
7874 0, /*tp_as_mapping*/
7875 0, /*tp_hash*/
7876 0, /*tp_call*/
7877 0, /*tp_str*/
7878 0, /*tp_getattro*/
7879 0, /*tp_setattro*/
7880 0, /*tp_as_buffer*/
7881 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7882 0, /*tp_doc*/
7883 0, /*tp_traverse*/
7884 0, /*tp_clear*/
7885 0, /*tp_richcompare*/
7886 0, /*tp_weaklistoffset*/
7887 0, /*tp_iter*/
7888 0, /*tp_iternext*/
7889 encoding_map_methods, /*tp_methods*/
7890 0, /*tp_members*/
7891 0, /*tp_getset*/
7892 0, /*tp_base*/
7893 0, /*tp_dict*/
7894 0, /*tp_descr_get*/
7895 0, /*tp_descr_set*/
7896 0, /*tp_dictoffset*/
7897 0, /*tp_init*/
7898 0, /*tp_alloc*/
7899 0, /*tp_new*/
7900 0, /*tp_free*/
7901 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007902};
7903
7904PyObject*
7905PyUnicode_BuildEncodingMap(PyObject* string)
7906{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907 PyObject *result;
7908 struct encoding_map *mresult;
7909 int i;
7910 int need_dict = 0;
7911 unsigned char level1[32];
7912 unsigned char level2[512];
7913 unsigned char *mlevel1, *mlevel2, *mlevel3;
7914 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007915 int kind;
7916 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007917 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007918 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007920 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007921 PyErr_BadArgument();
7922 return NULL;
7923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007924 kind = PyUnicode_KIND(string);
7925 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007926 length = PyUnicode_GET_LENGTH(string);
7927 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007928 memset(level1, 0xFF, sizeof level1);
7929 memset(level2, 0xFF, sizeof level2);
7930
7931 /* If there isn't a one-to-one mapping of NULL to \0,
7932 or if there are non-BMP characters, we need to use
7933 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007934 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007935 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007936 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007938 ch = PyUnicode_READ(kind, data, i);
7939 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940 need_dict = 1;
7941 break;
7942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007943 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944 /* unmapped character */
7945 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 l1 = ch >> 11;
7947 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007948 if (level1[l1] == 0xFF)
7949 level1[l1] = count2++;
7950 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007951 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 }
7953
7954 if (count2 >= 0xFF || count3 >= 0xFF)
7955 need_dict = 1;
7956
7957 if (need_dict) {
7958 PyObject *result = PyDict_New();
7959 PyObject *key, *value;
7960 if (!result)
7961 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007962 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007963 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007964 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 if (!key || !value)
7966 goto failed1;
7967 if (PyDict_SetItem(result, key, value) == -1)
7968 goto failed1;
7969 Py_DECREF(key);
7970 Py_DECREF(value);
7971 }
7972 return result;
7973 failed1:
7974 Py_XDECREF(key);
7975 Py_XDECREF(value);
7976 Py_DECREF(result);
7977 return NULL;
7978 }
7979
7980 /* Create a three-level trie */
7981 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7982 16*count2 + 128*count3 - 1);
7983 if (!result)
7984 return PyErr_NoMemory();
7985 PyObject_Init(result, &EncodingMapType);
7986 mresult = (struct encoding_map*)result;
7987 mresult->count2 = count2;
7988 mresult->count3 = count3;
7989 mlevel1 = mresult->level1;
7990 mlevel2 = mresult->level23;
7991 mlevel3 = mresult->level23 + 16*count2;
7992 memcpy(mlevel1, level1, 32);
7993 memset(mlevel2, 0xFF, 16*count2);
7994 memset(mlevel3, 0, 128*count3);
7995 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007996 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007997 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007998 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7999 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008000 /* unmapped character */
8001 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008002 o1 = ch>>11;
8003 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008004 i2 = 16*mlevel1[o1] + o2;
8005 if (mlevel2[i2] == 0xFF)
8006 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008007 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008008 i3 = 128*mlevel2[i2] + o3;
8009 mlevel3[i3] = i;
8010 }
8011 return result;
8012}
8013
8014static int
Victor Stinner22168992011-11-20 17:09:18 +01008015encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008016{
8017 struct encoding_map *map = (struct encoding_map*)mapping;
8018 int l1 = c>>11;
8019 int l2 = (c>>7) & 0xF;
8020 int l3 = c & 0x7F;
8021 int i;
8022
Victor Stinner22168992011-11-20 17:09:18 +01008023 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 if (c == 0)
8026 return 0;
8027 /* level 1*/
8028 i = map->level1[l1];
8029 if (i == 0xFF) {
8030 return -1;
8031 }
8032 /* level 2*/
8033 i = map->level23[16*i+l2];
8034 if (i == 0xFF) {
8035 return -1;
8036 }
8037 /* level 3 */
8038 i = map->level23[16*map->count2 + 128*i + l3];
8039 if (i == 0) {
8040 return -1;
8041 }
8042 return i;
8043}
8044
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008045/* Lookup the character ch in the mapping. If the character
8046 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008047 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008049charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008050{
Christian Heimes217cfd12007-12-02 14:31:20 +00008051 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008052 PyObject *x;
8053
8054 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008055 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008056 x = PyObject_GetItem(mapping, w);
8057 Py_DECREF(w);
8058 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8060 /* No mapping found means: mapping is undefined. */
8061 PyErr_Clear();
8062 x = Py_None;
8063 Py_INCREF(x);
8064 return x;
8065 } else
8066 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008067 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008068 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008070 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 long value = PyLong_AS_LONG(x);
8072 if (value < 0 || value > 255) {
8073 PyErr_SetString(PyExc_TypeError,
8074 "character mapping must be in range(256)");
8075 Py_DECREF(x);
8076 return NULL;
8077 }
8078 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008080 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008082 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 /* wrong return value */
8084 PyErr_Format(PyExc_TypeError,
8085 "character mapping must return integer, bytes or None, not %.400s",
8086 x->ob_type->tp_name);
8087 Py_DECREF(x);
8088 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008089 }
8090}
8091
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008093charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008094{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008095 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8096 /* exponentially overallocate to minimize reallocations */
8097 if (requiredsize < 2*outsize)
8098 requiredsize = 2*outsize;
8099 if (_PyBytes_Resize(outobj, requiredsize))
8100 return -1;
8101 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102}
8103
Benjamin Peterson14339b62009-01-31 16:36:08 +00008104typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008106} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008108 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008109 space is available. Return a new reference to the object that
8110 was put in the output buffer, or Py_None, if the mapping was undefined
8111 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008112 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008113static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008114charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008115 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008116{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008117 PyObject *rep;
8118 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008119 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120
Christian Heimes90aa7642007-12-19 02:45:37 +00008121 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008124 if (res == -1)
8125 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 if (outsize<requiredsize)
8127 if (charmapencode_resize(outobj, outpos, requiredsize))
8128 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008129 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 outstart[(*outpos)++] = (char)res;
8131 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 }
8133
8134 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008137 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 Py_DECREF(rep);
8139 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008140 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008141 if (PyLong_Check(rep)) {
8142 Py_ssize_t requiredsize = *outpos+1;
8143 if (outsize<requiredsize)
8144 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8145 Py_DECREF(rep);
8146 return enc_EXCEPTION;
8147 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008148 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008150 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 else {
8152 const char *repchars = PyBytes_AS_STRING(rep);
8153 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8154 Py_ssize_t requiredsize = *outpos+repsize;
8155 if (outsize<requiredsize)
8156 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8157 Py_DECREF(rep);
8158 return enc_EXCEPTION;
8159 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008160 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 memcpy(outstart + *outpos, repchars, repsize);
8162 *outpos += repsize;
8163 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008164 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008165 Py_DECREF(rep);
8166 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008167}
8168
8169/* handle an error in PyUnicode_EncodeCharmap
8170 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008171static int
8172charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008173 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008174 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008175 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008176 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008177{
8178 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008179 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008180 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008181 enum PyUnicode_Kind kind;
8182 void *data;
8183 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008184 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008185 Py_ssize_t collstartpos = *inpos;
8186 Py_ssize_t collendpos = *inpos+1;
8187 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188 char *encoding = "charmap";
8189 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008192 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193
Benjamin Petersonbac79492012-01-14 13:34:47 -05008194 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008195 return -1;
8196 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 /* find all unencodable characters */
8198 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008200 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008201 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008202 val = encoding_map_lookup(ch, mapping);
8203 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 break;
8205 ++collendpos;
8206 continue;
8207 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008208
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008209 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8210 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 if (rep==NULL)
8212 return -1;
8213 else if (rep!=Py_None) {
8214 Py_DECREF(rep);
8215 break;
8216 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008217 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219 }
8220 /* cache callback name lookup
8221 * (if not done yet, i.e. it's the first error) */
8222 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 if ((errors==NULL) || (!strcmp(errors, "strict")))
8224 *known_errorHandler = 1;
8225 else if (!strcmp(errors, "replace"))
8226 *known_errorHandler = 2;
8227 else if (!strcmp(errors, "ignore"))
8228 *known_errorHandler = 3;
8229 else if (!strcmp(errors, "xmlcharrefreplace"))
8230 *known_errorHandler = 4;
8231 else
8232 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233 }
8234 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008235 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008236 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 return -1;
8238 case 2: /* replace */
8239 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 x = charmapencode_output('?', mapping, res, respos);
8241 if (x==enc_EXCEPTION) {
8242 return -1;
8243 }
8244 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008245 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 return -1;
8247 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008248 }
8249 /* fall through */
8250 case 3: /* ignore */
8251 *inpos = collendpos;
8252 break;
8253 case 4: /* xmlcharrefreplace */
8254 /* generate replacement (temporarily (mis)uses p) */
8255 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 char buffer[2+29+1+1];
8257 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008258 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 for (cp = buffer; *cp; ++cp) {
8260 x = charmapencode_output(*cp, mapping, res, respos);
8261 if (x==enc_EXCEPTION)
8262 return -1;
8263 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008264 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 return -1;
8266 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008267 }
8268 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008269 *inpos = collendpos;
8270 break;
8271 default:
8272 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008273 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008275 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008277 if (PyBytes_Check(repunicode)) {
8278 /* Directly copy bytes result to output. */
8279 Py_ssize_t outsize = PyBytes_Size(*res);
8280 Py_ssize_t requiredsize;
8281 repsize = PyBytes_Size(repunicode);
8282 requiredsize = *respos + repsize;
8283 if (requiredsize > outsize)
8284 /* Make room for all additional bytes. */
8285 if (charmapencode_resize(res, respos, requiredsize)) {
8286 Py_DECREF(repunicode);
8287 return -1;
8288 }
8289 memcpy(PyBytes_AsString(*res) + *respos,
8290 PyBytes_AsString(repunicode), repsize);
8291 *respos += repsize;
8292 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008293 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008294 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008296 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008297 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008298 Py_DECREF(repunicode);
8299 return -1;
8300 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008301 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008302 data = PyUnicode_DATA(repunicode);
8303 kind = PyUnicode_KIND(repunicode);
8304 for (index = 0; index < repsize; index++) {
8305 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8306 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008308 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 return -1;
8310 }
8311 else if (x==enc_FAILED) {
8312 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008313 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 return -1;
8315 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008316 }
8317 *inpos = newpos;
8318 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319 }
8320 return 0;
8321}
8322
Alexander Belopolsky40018472011-02-26 01:02:56 +00008323PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008324_PyUnicode_EncodeCharmap(PyObject *unicode,
8325 PyObject *mapping,
8326 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008327{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 /* output object */
8329 PyObject *res = NULL;
8330 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008331 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008332 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008334 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 PyObject *errorHandler = NULL;
8336 PyObject *exc = NULL;
8337 /* the following variable is used for caching string comparisons
8338 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8339 * 3=ignore, 4=xmlcharrefreplace */
8340 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008341 void *data;
8342 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343
Benjamin Petersonbac79492012-01-14 13:34:47 -05008344 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008345 return NULL;
8346 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008347 data = PyUnicode_DATA(unicode);
8348 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350 /* Default to Latin-1 */
8351 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008352 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 /* allocate enough for a simple encoding without
8355 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008356 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 if (res == NULL)
8358 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008359 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008363 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008365 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 if (x==enc_EXCEPTION) /* error */
8367 goto onError;
8368 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008369 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 &exc,
8371 &known_errorHandler, &errorHandler, errors,
8372 &res, &respos)) {
8373 goto onError;
8374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008375 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 else
8377 /* done with this character => adjust input position */
8378 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008379 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008382 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008383 if (_PyBytes_Resize(&res, respos) < 0)
8384 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008385
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 Py_XDECREF(exc);
8387 Py_XDECREF(errorHandler);
8388 return res;
8389
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 Py_XDECREF(res);
8392 Py_XDECREF(exc);
8393 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008394 return NULL;
8395}
8396
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397/* Deprecated */
8398PyObject *
8399PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8400 Py_ssize_t size,
8401 PyObject *mapping,
8402 const char *errors)
8403{
8404 PyObject *result;
8405 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8406 if (unicode == NULL)
8407 return NULL;
8408 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8409 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008410 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008411}
8412
Alexander Belopolsky40018472011-02-26 01:02:56 +00008413PyObject *
8414PyUnicode_AsCharmapString(PyObject *unicode,
8415 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008416{
8417 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 PyErr_BadArgument();
8419 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008420 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008421 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008422}
8423
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008424/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425static void
8426make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008427 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008428 Py_ssize_t startpos, Py_ssize_t endpos,
8429 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008430{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 *exceptionObject = _PyUnicodeTranslateError_Create(
8433 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434 }
8435 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8437 goto onError;
8438 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8439 goto onError;
8440 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8441 goto onError;
8442 return;
8443 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008444 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445 }
8446}
8447
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448/* error handling callback helper:
8449 build arguments, call the callback and check the arguments,
8450 put the result into newpos and return the replacement string, which
8451 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008452static PyObject *
8453unicode_translate_call_errorhandler(const char *errors,
8454 PyObject **errorHandler,
8455 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008456 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008457 Py_ssize_t startpos, Py_ssize_t endpos,
8458 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008460 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008462 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463 PyObject *restuple;
8464 PyObject *resunicode;
8465
8466 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 }
8471
8472 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008473 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476
8477 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008481 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008482 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 Py_DECREF(restuple);
8484 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 }
8486 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 &resunicode, &i_newpos)) {
8488 Py_DECREF(restuple);
8489 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008490 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008491 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008493 else
8494 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008496 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 Py_DECREF(restuple);
8498 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008499 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 Py_INCREF(resunicode);
8501 Py_DECREF(restuple);
8502 return resunicode;
8503}
8504
8505/* Lookup the character ch in the mapping and put the result in result,
8506 which must be decrefed by the caller.
8507 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008508static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510{
Christian Heimes217cfd12007-12-02 14:31:20 +00008511 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 PyObject *x;
8513
8514 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 x = PyObject_GetItem(mapping, w);
8517 Py_DECREF(w);
8518 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8520 /* No mapping found means: use 1:1 mapping. */
8521 PyErr_Clear();
8522 *result = NULL;
8523 return 0;
8524 } else
8525 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 }
8527 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 *result = x;
8529 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008531 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 long value = PyLong_AS_LONG(x);
8533 long max = PyUnicode_GetMax();
8534 if (value < 0 || value > max) {
8535 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008536 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 Py_DECREF(x);
8538 return -1;
8539 }
8540 *result = x;
8541 return 0;
8542 }
8543 else if (PyUnicode_Check(x)) {
8544 *result = x;
8545 return 0;
8546 }
8547 else {
8548 /* wrong return value */
8549 PyErr_SetString(PyExc_TypeError,
8550 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008551 Py_DECREF(x);
8552 return -1;
8553 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554}
8555/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 if not reallocate and adjust various state variables.
8557 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008558static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 Py_ssize_t oldsize = *psize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008563 Py_UCS4 *new_outobj;
Walter Dörwald4894c302003-10-24 14:25:28 +00008564 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 /* exponentially overallocate to minimize reallocations */
8566 if (requiredsize < 2 * oldsize)
8567 requiredsize = 2 * oldsize;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008568 new_outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8569 if (new_outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 return -1;
Kristjan Valur Jonsson85634d72012-05-31 09:37:31 +00008571 *outobj = new_outobj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573 }
8574 return 0;
8575}
8576/* lookup the character, put the result in the output string and adjust
8577 various state variables. Return a new reference to the object that
8578 was put in the output buffer in *result, or Py_None, if the mapping was
8579 undefined (in which case no character was written).
8580 The called must decref result.
8581 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008582static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008583charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8584 PyObject *mapping, Py_UCS4 **output,
8585 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008586 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8589 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 }
8595 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008597 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008600 }
8601 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 Py_ssize_t repsize;
8603 if (PyUnicode_READY(*res) == -1)
8604 return -1;
8605 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 if (repsize==1) {
8607 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 }
8610 else if (repsize!=0) {
8611 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 Py_ssize_t requiredsize = *opos +
8613 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 Py_ssize_t i;
8616 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 for(i = 0; i < repsize; i++)
8619 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621 }
8622 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 return 0;
8625}
8626
Alexander Belopolsky40018472011-02-26 01:02:56 +00008627PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628_PyUnicode_TranslateCharmap(PyObject *input,
8629 PyObject *mapping,
8630 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008631{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 /* input object */
8633 char *idata;
8634 Py_ssize_t size, i;
8635 int kind;
8636 /* output buffer */
8637 Py_UCS4 *output = NULL;
8638 Py_ssize_t osize;
8639 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 char *reason = "character maps to <undefined>";
8643 PyObject *errorHandler = NULL;
8644 PyObject *exc = NULL;
8645 /* the following variable is used for caching string comparisons
8646 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8647 * 3=ignore, 4=xmlcharrefreplace */
8648 int known_errorHandler = -1;
8649
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 PyErr_BadArgument();
8652 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008653 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 if (PyUnicode_READY(input) == -1)
8656 return NULL;
8657 idata = (char*)PyUnicode_DATA(input);
8658 kind = PyUnicode_KIND(input);
8659 size = PyUnicode_GET_LENGTH(input);
8660 i = 0;
8661
8662 if (size == 0) {
8663 Py_INCREF(input);
8664 return input;
8665 }
8666
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008667 /* allocate enough for a simple 1:1 translation without
8668 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 osize = size;
Benjamin Petersone5a853c2015-03-02 13:23:25 -05008670 output = PyMem_NEW(Py_UCS4, osize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 opos = 0;
8672 if (output == NULL) {
8673 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 /* try to encode it */
8679 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680 if (charmaptranslate_output(input, i, mapping,
8681 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 Py_XDECREF(x);
8683 goto onError;
8684 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008685 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 else { /* untranslatable character */
8689 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8690 Py_ssize_t repsize;
8691 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008693 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 Py_ssize_t collstart = i;
8695 Py_ssize_t collend = i+1;
8696 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 while (collend < size) {
8700 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 goto onError;
8702 Py_XDECREF(x);
8703 if (x!=Py_None)
8704 break;
8705 ++collend;
8706 }
8707 /* cache callback name lookup
8708 * (if not done yet, i.e. it's the first error) */
8709 if (known_errorHandler==-1) {
8710 if ((errors==NULL) || (!strcmp(errors, "strict")))
8711 known_errorHandler = 1;
8712 else if (!strcmp(errors, "replace"))
8713 known_errorHandler = 2;
8714 else if (!strcmp(errors, "ignore"))
8715 known_errorHandler = 3;
8716 else if (!strcmp(errors, "xmlcharrefreplace"))
8717 known_errorHandler = 4;
8718 else
8719 known_errorHandler = 0;
8720 }
8721 switch (known_errorHandler) {
8722 case 1: /* strict */
Victor Stinner6fa62752012-10-23 02:51:50 +02008723 make_translate_exception(&exc,
8724 input, collstart, collend, reason);
8725 if (exc != NULL)
8726 PyCodec_StrictErrors(exc);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008727 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 case 2: /* replace */
8729 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008730 for (coll = collstart; coll<collend; coll++)
8731 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 /* fall through */
8733 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 break;
8736 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 /* generate replacement (temporarily (mis)uses i) */
8738 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 char buffer[2+29+1+1];
8740 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8742 if (charmaptranslate_makespace(&output, &osize,
8743 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 goto onError;
8745 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 break;
8750 default:
8751 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 reason, input, &exc,
8753 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008754 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008756 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008757 Py_DECREF(repunicode);
8758 goto onError;
8759 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761 repsize = PyUnicode_GET_LENGTH(repunicode);
8762 if (charmaptranslate_makespace(&output, &osize,
8763 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 Py_DECREF(repunicode);
8765 goto onError;
8766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 for (uni2 = 0; repsize-->0; ++uni2)
8768 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8769 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008771 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008772 }
8773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008774 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8775 if (!res)
8776 goto onError;
8777 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008778 Py_XDECREF(exc);
8779 Py_XDECREF(errorHandler);
8780 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008784 Py_XDECREF(exc);
8785 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786 return NULL;
8787}
8788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008789/* Deprecated. Use PyUnicode_Translate instead. */
8790PyObject *
8791PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8792 Py_ssize_t size,
8793 PyObject *mapping,
8794 const char *errors)
8795{
Christian Heimes5f520f42012-09-11 14:03:25 +02008796 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8798 if (!unicode)
8799 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008800 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8801 Py_DECREF(unicode);
8802 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008803}
8804
Alexander Belopolsky40018472011-02-26 01:02:56 +00008805PyObject *
8806PyUnicode_Translate(PyObject *str,
8807 PyObject *mapping,
8808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008809{
8810 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008811
Guido van Rossumd57fd912000-03-10 22:53:23 +00008812 str = PyUnicode_FromObject(str);
8813 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008814 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008815 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008816 Py_DECREF(str);
8817 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008818}
Tim Petersced69f82003-09-16 20:30:58 +00008819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008820static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008821fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822{
8823 /* No need to call PyUnicode_READY(self) because this function is only
8824 called as a callback from fixup() which does it already. */
8825 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8826 const int kind = PyUnicode_KIND(self);
8827 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008828 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008829 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 Py_ssize_t i;
8831
8832 for (i = 0; i < len; ++i) {
8833 ch = PyUnicode_READ(kind, data, i);
8834 fixed = 0;
8835 if (ch > 127) {
8836 if (Py_UNICODE_ISSPACE(ch))
8837 fixed = ' ';
8838 else {
8839 const int decimal = Py_UNICODE_TODECIMAL(ch);
8840 if (decimal >= 0)
8841 fixed = '0' + decimal;
8842 }
8843 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008844 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008845 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 PyUnicode_WRITE(kind, data, i, fixed);
8847 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008848 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008849 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851 }
8852
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008853 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008854}
8855
8856PyObject *
8857_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8858{
8859 if (!PyUnicode_Check(unicode)) {
8860 PyErr_BadInternalCall();
8861 return NULL;
8862 }
8863 if (PyUnicode_READY(unicode) == -1)
8864 return NULL;
8865 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8866 /* If the string is already ASCII, just return the same string */
8867 Py_INCREF(unicode);
8868 return unicode;
8869 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008870 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871}
8872
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008873PyObject *
8874PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8875 Py_ssize_t length)
8876{
Victor Stinnerf0124502011-11-21 23:12:56 +01008877 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008878 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008879 Py_UCS4 maxchar;
8880 enum PyUnicode_Kind kind;
8881 void *data;
8882
Victor Stinner99d7ad02012-02-22 13:37:39 +01008883 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008884 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008885 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008886 if (ch > 127) {
8887 int decimal = Py_UNICODE_TODECIMAL(ch);
8888 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008889 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008890 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008891 }
8892 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008893
8894 /* Copy to a new string */
8895 decimal = PyUnicode_New(length, maxchar);
8896 if (decimal == NULL)
8897 return decimal;
8898 kind = PyUnicode_KIND(decimal);
8899 data = PyUnicode_DATA(decimal);
8900 /* Iterate over code points */
8901 for (i = 0; i < length; i++) {
8902 Py_UNICODE ch = s[i];
8903 if (ch > 127) {
8904 int decimal = Py_UNICODE_TODECIMAL(ch);
8905 if (decimal >= 0)
8906 ch = '0' + decimal;
8907 }
8908 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008909 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008910 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008911}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008912/* --- Decimal Encoder ---------------------------------------------------- */
8913
Alexander Belopolsky40018472011-02-26 01:02:56 +00008914int
8915PyUnicode_EncodeDecimal(Py_UNICODE *s,
8916 Py_ssize_t length,
8917 char *output,
8918 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008919{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008920 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008921 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008922 enum PyUnicode_Kind kind;
8923 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008924
8925 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 PyErr_BadArgument();
8927 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008928 }
8929
Victor Stinner42bf7752011-11-21 22:52:58 +01008930 unicode = PyUnicode_FromUnicode(s, length);
8931 if (unicode == NULL)
8932 return -1;
8933
Benjamin Petersonbac79492012-01-14 13:34:47 -05008934 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008935 Py_DECREF(unicode);
8936 return -1;
8937 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008938 kind = PyUnicode_KIND(unicode);
8939 data = PyUnicode_DATA(unicode);
8940
Victor Stinnerb84d7232011-11-22 01:50:07 +01008941 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008942 PyObject *exc;
8943 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008945 Py_ssize_t startpos;
8946
8947 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008948
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008950 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008951 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008953 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008954 decimal = Py_UNICODE_TODECIMAL(ch);
8955 if (decimal >= 0) {
8956 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008957 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 continue;
8959 }
8960 if (0 < ch && ch < 256) {
8961 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008962 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008963 continue;
8964 }
Victor Stinner6345be92011-11-25 20:09:01 +01008965
Victor Stinner42bf7752011-11-21 22:52:58 +01008966 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008967 exc = NULL;
8968 raise_encode_exception(&exc, "decimal", unicode,
8969 startpos, startpos+1,
8970 "invalid decimal Unicode string");
8971 Py_XDECREF(exc);
8972 Py_DECREF(unicode);
8973 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008974 }
8975 /* 0-terminate the output string */
8976 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008977 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008978 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008979}
8980
Guido van Rossumd57fd912000-03-10 22:53:23 +00008981/* --- Helpers ------------------------------------------------------------ */
8982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008984any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985 Py_ssize_t start,
8986 Py_ssize_t end)
8987{
8988 int kind1, kind2, kind;
8989 void *buf1, *buf2;
8990 Py_ssize_t len1, len2, result;
8991
8992 kind1 = PyUnicode_KIND(s1);
8993 kind2 = PyUnicode_KIND(s2);
8994 kind = kind1 > kind2 ? kind1 : kind2;
8995 buf1 = PyUnicode_DATA(s1);
8996 buf2 = PyUnicode_DATA(s2);
8997 if (kind1 != kind)
8998 buf1 = _PyUnicode_AsKind(s1, kind);
8999 if (!buf1)
9000 return -2;
9001 if (kind2 != kind)
9002 buf2 = _PyUnicode_AsKind(s2, kind);
9003 if (!buf2) {
9004 if (kind1 != kind) PyMem_Free(buf1);
9005 return -2;
9006 }
9007 len1 = PyUnicode_GET_LENGTH(s1);
9008 len2 = PyUnicode_GET_LENGTH(s2);
9009
Victor Stinner794d5672011-10-10 03:21:36 +02009010 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009011 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009012 case PyUnicode_1BYTE_KIND:
9013 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9014 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9015 else
9016 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9017 break;
9018 case PyUnicode_2BYTE_KIND:
9019 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9020 break;
9021 case PyUnicode_4BYTE_KIND:
9022 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9023 break;
9024 default:
9025 assert(0); result = -2;
9026 }
9027 }
9028 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009029 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009030 case PyUnicode_1BYTE_KIND:
9031 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9032 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9033 else
9034 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9035 break;
9036 case PyUnicode_2BYTE_KIND:
9037 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9038 break;
9039 case PyUnicode_4BYTE_KIND:
9040 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9041 break;
9042 default:
9043 assert(0); result = -2;
9044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045 }
9046
9047 if (kind1 != kind)
9048 PyMem_Free(buf1);
9049 if (kind2 != kind)
9050 PyMem_Free(buf2);
9051
9052 return result;
9053}
9054
9055Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009056_PyUnicode_InsertThousandsGrouping(
9057 PyObject *unicode, Py_ssize_t index,
9058 Py_ssize_t n_buffer,
9059 void *digits, Py_ssize_t n_digits,
9060 Py_ssize_t min_width,
9061 const char *grouping, PyObject *thousands_sep,
9062 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063{
Victor Stinner41a863c2012-02-24 00:37:51 +01009064 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009065 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009066 Py_ssize_t thousands_sep_len;
9067 Py_ssize_t len;
9068
9069 if (unicode != NULL) {
9070 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009071 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009072 }
9073 else {
9074 kind = PyUnicode_1BYTE_KIND;
9075 data = NULL;
9076 }
9077 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9078 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9079 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9080 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009081 if (thousands_sep_kind < kind) {
9082 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9083 if (!thousands_sep_data)
9084 return -1;
9085 }
9086 else {
9087 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9088 if (!data)
9089 return -1;
9090 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009091 }
9092
Benjamin Petersonead6b532011-12-20 17:23:42 -06009093 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009094 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009095 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009096 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009097 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009098 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009099 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009100 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009101 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009102 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009103 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009104 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009105 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009107 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009108 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009109 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009110 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009111 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009113 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009114 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009115 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009116 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009117 break;
9118 default:
9119 assert(0);
9120 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009122 if (unicode != NULL && thousands_sep_kind != kind) {
9123 if (thousands_sep_kind < kind)
9124 PyMem_Free(thousands_sep_data);
9125 else
9126 PyMem_Free(data);
9127 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009128 if (unicode == NULL) {
9129 *maxchar = 127;
9130 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009131 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009132 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009133 }
9134 }
9135 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136}
9137
9138
Thomas Wouters477c8d52006-05-27 19:21:47 +00009139/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009140#define ADJUST_INDICES(start, end, len) \
9141 if (end > len) \
9142 end = len; \
9143 else if (end < 0) { \
9144 end += len; \
9145 if (end < 0) \
9146 end = 0; \
9147 } \
9148 if (start < 0) { \
9149 start += len; \
9150 if (start < 0) \
9151 start = 0; \
9152 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009153
Alexander Belopolsky40018472011-02-26 01:02:56 +00009154Py_ssize_t
9155PyUnicode_Count(PyObject *str,
9156 PyObject *substr,
9157 Py_ssize_t start,
9158 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009159{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009160 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009161 PyObject* str_obj;
9162 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 int kind1, kind2, kind;
9164 void *buf1 = NULL, *buf2 = NULL;
9165 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009166
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009167 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009168 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009169 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009170 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009171 if (!sub_obj) {
9172 Py_DECREF(str_obj);
9173 return -1;
9174 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009175 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009176 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009177 Py_DECREF(str_obj);
9178 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179 }
Tim Petersced69f82003-09-16 20:30:58 +00009180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 kind1 = PyUnicode_KIND(str_obj);
9182 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009183 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009186 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009187 if (kind2 > kind) {
9188 Py_DECREF(sub_obj);
9189 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009190 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009191 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009192 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009193 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 if (!buf2)
9195 goto onError;
9196 len1 = PyUnicode_GET_LENGTH(str_obj);
9197 len2 = PyUnicode_GET_LENGTH(sub_obj);
9198
9199 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009200 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009202 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9203 result = asciilib_count(
9204 ((Py_UCS1*)buf1) + start, end - start,
9205 buf2, len2, PY_SSIZE_T_MAX
9206 );
9207 else
9208 result = ucs1lib_count(
9209 ((Py_UCS1*)buf1) + start, end - start,
9210 buf2, len2, PY_SSIZE_T_MAX
9211 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 break;
9213 case PyUnicode_2BYTE_KIND:
9214 result = ucs2lib_count(
9215 ((Py_UCS2*)buf1) + start, end - start,
9216 buf2, len2, PY_SSIZE_T_MAX
9217 );
9218 break;
9219 case PyUnicode_4BYTE_KIND:
9220 result = ucs4lib_count(
9221 ((Py_UCS4*)buf1) + start, end - start,
9222 buf2, len2, PY_SSIZE_T_MAX
9223 );
9224 break;
9225 default:
9226 assert(0); result = 0;
9227 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009228
9229 Py_DECREF(sub_obj);
9230 Py_DECREF(str_obj);
9231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 if (kind2 != kind)
9233 PyMem_Free(buf2);
9234
Guido van Rossumd57fd912000-03-10 22:53:23 +00009235 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 onError:
9237 Py_DECREF(sub_obj);
9238 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 if (kind2 != kind && buf2)
9240 PyMem_Free(buf2);
9241 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242}
9243
Alexander Belopolsky40018472011-02-26 01:02:56 +00009244Py_ssize_t
9245PyUnicode_Find(PyObject *str,
9246 PyObject *sub,
9247 Py_ssize_t start,
9248 Py_ssize_t end,
9249 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009251 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009252
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009254 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009255 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009256 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009257 if (!sub) {
9258 Py_DECREF(str);
9259 return -2;
9260 }
9261 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9262 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009263 Py_DECREF(str);
9264 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 }
Tim Petersced69f82003-09-16 20:30:58 +00009266
Victor Stinner794d5672011-10-10 03:21:36 +02009267 result = any_find_slice(direction,
9268 str, sub, start, end
9269 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009272 Py_DECREF(sub);
9273
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274 return result;
9275}
9276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277Py_ssize_t
9278PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9279 Py_ssize_t start, Py_ssize_t end,
9280 int direction)
9281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009283 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009284 if (PyUnicode_READY(str) == -1)
9285 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009286 if (start < 0 || end < 0) {
9287 PyErr_SetString(PyExc_IndexError, "string index out of range");
9288 return -2;
9289 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290 if (end > PyUnicode_GET_LENGTH(str))
9291 end = PyUnicode_GET_LENGTH(str);
9292 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009293 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9294 kind, end-start, ch, direction);
9295 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009297 else
9298 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299}
9300
Alexander Belopolsky40018472011-02-26 01:02:56 +00009301static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009302tailmatch(PyObject *self,
9303 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009304 Py_ssize_t start,
9305 Py_ssize_t end,
9306 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 int kind_self;
9309 int kind_sub;
9310 void *data_self;
9311 void *data_sub;
9312 Py_ssize_t offset;
9313 Py_ssize_t i;
9314 Py_ssize_t end_sub;
9315
9316 if (PyUnicode_READY(self) == -1 ||
9317 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009318 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319
9320 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009321 return 1;
9322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009323 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9324 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009326 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 kind_self = PyUnicode_KIND(self);
9329 data_self = PyUnicode_DATA(self);
9330 kind_sub = PyUnicode_KIND(substring);
9331 data_sub = PyUnicode_DATA(substring);
9332 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9333
9334 if (direction > 0)
9335 offset = end;
9336 else
9337 offset = start;
9338
9339 if (PyUnicode_READ(kind_self, data_self, offset) ==
9340 PyUnicode_READ(kind_sub, data_sub, 0) &&
9341 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9342 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9343 /* If both are of the same kind, memcmp is sufficient */
9344 if (kind_self == kind_sub) {
9345 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009346 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 data_sub,
9348 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009349 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 }
9351 /* otherwise we have to compare each character by first accesing it */
9352 else {
9353 /* We do not need to compare 0 and len(substring)-1 because
9354 the if statement above ensured already that they are equal
9355 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 for (i = 1; i < end_sub; ++i) {
9357 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9358 PyUnicode_READ(kind_sub, data_sub, i))
9359 return 0;
9360 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009361 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363 }
9364
9365 return 0;
9366}
9367
Alexander Belopolsky40018472011-02-26 01:02:56 +00009368Py_ssize_t
9369PyUnicode_Tailmatch(PyObject *str,
9370 PyObject *substr,
9371 Py_ssize_t start,
9372 Py_ssize_t end,
9373 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009375 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009376
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 str = PyUnicode_FromObject(str);
9378 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 substr = PyUnicode_FromObject(substr);
9381 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009382 Py_DECREF(str);
9383 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 }
Tim Petersced69f82003-09-16 20:30:58 +00009385
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009386 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009387 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 Py_DECREF(str);
9389 Py_DECREF(substr);
9390 return result;
9391}
9392
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393/* Apply fixfct filter to the Unicode object self and return a
9394 reference to the modified object */
9395
Alexander Belopolsky40018472011-02-26 01:02:56 +00009396static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009397fixup(PyObject *self,
9398 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009399{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 PyObject *u;
9401 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009402 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009403
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009404 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009405 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009406 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009407 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 /* fix functions return the new maximum character in a string,
9410 if the kind of the resulting unicode object does not change,
9411 everything is fine. Otherwise we need to change the string kind
9412 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009413 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009414
9415 if (maxchar_new == 0) {
9416 /* no changes */;
9417 if (PyUnicode_CheckExact(self)) {
9418 Py_DECREF(u);
9419 Py_INCREF(self);
9420 return self;
9421 }
9422 else
9423 return u;
9424 }
9425
Victor Stinnere6abb482012-05-02 01:15:40 +02009426 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427
Victor Stinnereaab6042011-12-11 22:22:39 +01009428 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009430
9431 /* In case the maximum character changed, we need to
9432 convert the string to the new category. */
9433 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9434 if (v == NULL) {
9435 Py_DECREF(u);
9436 return NULL;
9437 }
9438 if (maxchar_new > maxchar_old) {
9439 /* If the maxchar increased so that the kind changed, not all
9440 characters are representable anymore and we need to fix the
9441 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009442 _PyUnicode_FastCopyCharacters(v, 0,
9443 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009444 maxchar_old = fixfct(v);
9445 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 }
9447 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009448 _PyUnicode_FastCopyCharacters(v, 0,
9449 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009451 Py_DECREF(u);
9452 assert(_PyUnicode_CheckConsistency(v, 1));
9453 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454}
9455
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009456static PyObject *
9457ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009458{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009459 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9460 char *resdata, *data = PyUnicode_DATA(self);
9461 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009462
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009463 res = PyUnicode_New(len, 127);
9464 if (res == NULL)
9465 return NULL;
9466 resdata = PyUnicode_DATA(res);
9467 if (lower)
9468 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009470 _Py_bytes_upper(resdata, data, len);
9471 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472}
9473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009475handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009476{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009477 Py_ssize_t j;
9478 int final_sigma;
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02009479 Py_UCS4 c = 0;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009480 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009481
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009482 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9483
9484 where ! is a negation and \p{xxx} is a character with property xxx.
9485 */
9486 for (j = i - 1; j >= 0; j--) {
9487 c = PyUnicode_READ(kind, data, j);
9488 if (!_PyUnicode_IsCaseIgnorable(c))
9489 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009491 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9492 if (final_sigma) {
9493 for (j = i + 1; j < length; j++) {
9494 c = PyUnicode_READ(kind, data, j);
9495 if (!_PyUnicode_IsCaseIgnorable(c))
9496 break;
9497 }
9498 final_sigma = j == length || !_PyUnicode_IsCased(c);
9499 }
9500 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501}
9502
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009503static int
9504lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9505 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507 /* Obscure special case. */
9508 if (c == 0x3A3) {
9509 mapped[0] = handle_capital_sigma(kind, data, length, i);
9510 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009512 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513}
9514
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009515static Py_ssize_t
9516do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009517{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009518 Py_ssize_t i, k = 0;
9519 int n_res, j;
9520 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009521
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522 c = PyUnicode_READ(kind, data, 0);
9523 n_res = _PyUnicode_ToUpperFull(c, mapped);
9524 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009525 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009526 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009528 for (i = 1; i < length; i++) {
9529 c = PyUnicode_READ(kind, data, i);
9530 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9531 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009532 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009533 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009534 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009535 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537}
9538
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009539static Py_ssize_t
9540do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9541 Py_ssize_t i, k = 0;
9542
9543 for (i = 0; i < length; i++) {
9544 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9545 int n_res, j;
9546 if (Py_UNICODE_ISUPPER(c)) {
9547 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9548 }
9549 else if (Py_UNICODE_ISLOWER(c)) {
9550 n_res = _PyUnicode_ToUpperFull(c, mapped);
9551 }
9552 else {
9553 n_res = 1;
9554 mapped[0] = c;
9555 }
9556 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009557 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009558 res[k++] = mapped[j];
9559 }
9560 }
9561 return k;
9562}
9563
9564static Py_ssize_t
9565do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9566 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009568 Py_ssize_t i, k = 0;
9569
9570 for (i = 0; i < length; i++) {
9571 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9572 int n_res, j;
9573 if (lower)
9574 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9575 else
9576 n_res = _PyUnicode_ToUpperFull(c, mapped);
9577 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009578 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009579 res[k++] = mapped[j];
9580 }
9581 }
9582 return k;
9583}
9584
9585static Py_ssize_t
9586do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9587{
9588 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9589}
9590
9591static Py_ssize_t
9592do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9593{
9594 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9595}
9596
Benjamin Petersone51757f2012-01-12 21:10:29 -05009597static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009598do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9599{
9600 Py_ssize_t i, k = 0;
9601
9602 for (i = 0; i < length; i++) {
9603 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9604 Py_UCS4 mapped[3];
9605 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9606 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009607 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009608 res[k++] = mapped[j];
9609 }
9610 }
9611 return k;
9612}
9613
9614static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009615do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9616{
9617 Py_ssize_t i, k = 0;
9618 int previous_is_cased;
9619
9620 previous_is_cased = 0;
9621 for (i = 0; i < length; i++) {
9622 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9623 Py_UCS4 mapped[3];
9624 int n_res, j;
9625
9626 if (previous_is_cased)
9627 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9628 else
9629 n_res = _PyUnicode_ToTitleFull(c, mapped);
9630
9631 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009632 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009633 res[k++] = mapped[j];
9634 }
9635
9636 previous_is_cased = _PyUnicode_IsCased(c);
9637 }
9638 return k;
9639}
9640
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009641static PyObject *
9642case_operation(PyObject *self,
9643 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9644{
9645 PyObject *res = NULL;
9646 Py_ssize_t length, newlength = 0;
9647 int kind, outkind;
9648 void *data, *outdata;
9649 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9650
Benjamin Petersoneea48462012-01-16 14:28:50 -05009651 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009652
9653 kind = PyUnicode_KIND(self);
9654 data = PyUnicode_DATA(self);
9655 length = PyUnicode_GET_LENGTH(self);
Antoine Pitroub6dc9b72014-10-15 23:14:53 +02009656 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009657 PyErr_SetString(PyExc_OverflowError, "string is too long");
9658 return NULL;
9659 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009660 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661 if (tmp == NULL)
9662 return PyErr_NoMemory();
9663 newlength = perform(kind, data, length, tmp, &maxchar);
9664 res = PyUnicode_New(newlength, maxchar);
9665 if (res == NULL)
9666 goto leave;
9667 tmpend = tmp + newlength;
9668 outdata = PyUnicode_DATA(res);
9669 outkind = PyUnicode_KIND(res);
9670 switch (outkind) {
9671 case PyUnicode_1BYTE_KIND:
9672 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9673 break;
9674 case PyUnicode_2BYTE_KIND:
9675 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9676 break;
9677 case PyUnicode_4BYTE_KIND:
9678 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9679 break;
9680 default:
9681 assert(0);
9682 break;
9683 }
9684 leave:
9685 PyMem_FREE(tmp);
9686 return res;
9687}
9688
Tim Peters8ce9f162004-08-27 01:49:32 +00009689PyObject *
9690PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009692 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009693 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009694 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009695 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009696 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9697 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009698 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009700 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009702 int use_memcpy;
9703 unsigned char *res_data = NULL, *sep_data = NULL;
9704 PyObject *last_obj;
9705 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009706
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009707 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009708 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009709 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009710 }
9711
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009712 /* NOTE: the following code can't call back into Python code,
9713 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009714 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009715
Tim Peters05eba1f2004-08-27 21:32:02 +00009716 seqlen = PySequence_Fast_GET_SIZE(fseq);
9717 /* If empty sequence, return u"". */
9718 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009719 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009720 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009721 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009722
Tim Peters05eba1f2004-08-27 21:32:02 +00009723 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009724 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009725 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009726 if (seqlen == 1) {
9727 if (PyUnicode_CheckExact(items[0])) {
9728 res = items[0];
9729 Py_INCREF(res);
9730 Py_DECREF(fseq);
9731 return res;
9732 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009733 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009734 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009735 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009736 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009737 /* Set up sep and seplen */
9738 if (separator == NULL) {
9739 /* fall back to a blank space separator */
9740 sep = PyUnicode_FromOrdinal(' ');
9741 if (!sep)
9742 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009743 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009744 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009745 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009746 else {
9747 if (!PyUnicode_Check(separator)) {
9748 PyErr_Format(PyExc_TypeError,
9749 "separator: expected str instance,"
9750 " %.80s found",
9751 Py_TYPE(separator)->tp_name);
9752 goto onError;
9753 }
9754 if (PyUnicode_READY(separator))
9755 goto onError;
9756 sep = separator;
9757 seplen = PyUnicode_GET_LENGTH(separator);
9758 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9759 /* inc refcount to keep this code path symmetric with the
9760 above case of a blank separator */
9761 Py_INCREF(sep);
9762 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009763 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009764 }
9765
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009766 /* There are at least two things to join, or else we have a subclass
9767 * of str in the sequence.
9768 * Do a pre-pass to figure out the total amount of space we'll
9769 * need (sz), and see whether all argument are strings.
9770 */
9771 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009772#ifdef Py_DEBUG
9773 use_memcpy = 0;
9774#else
9775 use_memcpy = 1;
9776#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009777 for (i = 0; i < seqlen; i++) {
9778 const Py_ssize_t old_sz = sz;
9779 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009780 if (!PyUnicode_Check(item)) {
9781 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009782 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009783 " %.80s found",
9784 i, Py_TYPE(item)->tp_name);
9785 goto onError;
9786 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009787 if (PyUnicode_READY(item) == -1)
9788 goto onError;
9789 sz += PyUnicode_GET_LENGTH(item);
9790 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009791 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009792 if (i != 0)
9793 sz += seplen;
9794 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9795 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009796 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009797 goto onError;
9798 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009799 if (use_memcpy && last_obj != NULL) {
9800 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9801 use_memcpy = 0;
9802 }
9803 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 }
Tim Petersced69f82003-09-16 20:30:58 +00009805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009806 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009807 if (res == NULL)
9808 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009809
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009810 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009811#ifdef Py_DEBUG
9812 use_memcpy = 0;
9813#else
9814 if (use_memcpy) {
9815 res_data = PyUnicode_1BYTE_DATA(res);
9816 kind = PyUnicode_KIND(res);
9817 if (seplen != 0)
9818 sep_data = PyUnicode_1BYTE_DATA(sep);
9819 }
9820#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009821 if (use_memcpy) {
9822 for (i = 0; i < seqlen; ++i) {
9823 Py_ssize_t itemlen;
9824 item = items[i];
9825
9826 /* Copy item, and maybe the separator. */
9827 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009828 Py_MEMCPY(res_data,
9829 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009830 kind * seplen);
9831 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009832 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009833
9834 itemlen = PyUnicode_GET_LENGTH(item);
9835 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009836 Py_MEMCPY(res_data,
9837 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009838 kind * itemlen);
9839 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009840 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009841 }
9842 assert(res_data == PyUnicode_1BYTE_DATA(res)
9843 + kind * PyUnicode_GET_LENGTH(res));
9844 }
9845 else {
9846 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9847 Py_ssize_t itemlen;
9848 item = items[i];
9849
9850 /* Copy item, and maybe the separator. */
9851 if (i && seplen != 0) {
9852 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9853 res_offset += seplen;
9854 }
9855
9856 itemlen = PyUnicode_GET_LENGTH(item);
9857 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009858 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009859 res_offset += itemlen;
9860 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009861 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009862 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009863 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009864
Tim Peters05eba1f2004-08-27 21:32:02 +00009865 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009867 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009868 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009869
Benjamin Peterson29060642009-01-31 22:14:21 +00009870 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009871 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009873 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874 return NULL;
9875}
9876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877#define FILL(kind, data, value, start, length) \
9878 do { \
9879 Py_ssize_t i_ = 0; \
9880 assert(kind != PyUnicode_WCHAR_KIND); \
9881 switch ((kind)) { \
9882 case PyUnicode_1BYTE_KIND: { \
9883 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009884 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009885 break; \
9886 } \
9887 case PyUnicode_2BYTE_KIND: { \
9888 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9889 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9890 break; \
9891 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009892 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9894 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9895 break; \
9896 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009897 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009898 } \
9899 } while (0)
9900
Victor Stinnerd3f08822012-05-29 12:57:52 +02009901void
9902_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9903 Py_UCS4 fill_char)
9904{
9905 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9906 const void *data = PyUnicode_DATA(unicode);
9907 assert(PyUnicode_IS_READY(unicode));
9908 assert(unicode_modifiable(unicode));
9909 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9910 assert(start >= 0);
9911 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9912 FILL(kind, data, fill_char, start, length);
9913}
9914
Victor Stinner3fe55312012-01-04 00:33:50 +01009915Py_ssize_t
9916PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9917 Py_UCS4 fill_char)
9918{
9919 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009920
9921 if (!PyUnicode_Check(unicode)) {
9922 PyErr_BadInternalCall();
9923 return -1;
9924 }
9925 if (PyUnicode_READY(unicode) == -1)
9926 return -1;
9927 if (unicode_check_modifiable(unicode))
9928 return -1;
9929
Victor Stinnerd3f08822012-05-29 12:57:52 +02009930 if (start < 0) {
9931 PyErr_SetString(PyExc_IndexError, "string index out of range");
9932 return -1;
9933 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009934 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9935 PyErr_SetString(PyExc_ValueError,
9936 "fill character is bigger than "
9937 "the string maximum character");
9938 return -1;
9939 }
9940
9941 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9942 length = Py_MIN(maxlen, length);
9943 if (length <= 0)
9944 return 0;
9945
Victor Stinnerd3f08822012-05-29 12:57:52 +02009946 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009947 return length;
9948}
9949
Victor Stinner9310abb2011-10-05 00:59:23 +02009950static PyObject *
9951pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009952 Py_ssize_t left,
9953 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009954 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 PyObject *u;
9957 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009958 int kind;
9959 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009960
9961 if (left < 0)
9962 left = 0;
9963 if (right < 0)
9964 right = 0;
9965
Victor Stinnerc4b49542011-12-11 22:44:26 +01009966 if (left == 0 && right == 0)
9967 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9970 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009971 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9972 return NULL;
9973 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009975 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009977 if (!u)
9978 return NULL;
9979
9980 kind = PyUnicode_KIND(u);
9981 data = PyUnicode_DATA(u);
9982 if (left)
9983 FILL(kind, data, fill, 0, left);
9984 if (right)
9985 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009986 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009987 assert(_PyUnicode_CheckConsistency(u, 1));
9988 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009989}
9990
Alexander Belopolsky40018472011-02-26 01:02:56 +00009991PyObject *
9992PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995
9996 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009997 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009998 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009999 if (PyUnicode_READY(string) == -1) {
10000 Py_DECREF(string);
10001 return NULL;
10002 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010003
Benjamin Petersonead6b532011-12-20 17:23:42 -060010004 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010005 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010006 if (PyUnicode_IS_ASCII(string))
10007 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010009 PyUnicode_GET_LENGTH(string), keepends);
10010 else
10011 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010012 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010013 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 break;
10015 case PyUnicode_2BYTE_KIND:
10016 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010017 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010018 PyUnicode_GET_LENGTH(string), keepends);
10019 break;
10020 case PyUnicode_4BYTE_KIND:
10021 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010022 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010023 PyUnicode_GET_LENGTH(string), keepends);
10024 break;
10025 default:
10026 assert(0);
10027 list = 0;
10028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010029 Py_DECREF(string);
10030 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010031}
10032
Alexander Belopolsky40018472011-02-26 01:02:56 +000010033static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010034split(PyObject *self,
10035 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010036 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010037{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 int kind1, kind2, kind;
10039 void *buf1, *buf2;
10040 Py_ssize_t len1, len2;
10041 PyObject* out;
10042
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010044 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 if (PyUnicode_READY(self) == -1)
10047 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010050 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010052 if (PyUnicode_IS_ASCII(self))
10053 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010054 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010055 PyUnicode_GET_LENGTH(self), maxcount
10056 );
10057 else
10058 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010059 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010060 PyUnicode_GET_LENGTH(self), maxcount
10061 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 case PyUnicode_2BYTE_KIND:
10063 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010064 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 PyUnicode_GET_LENGTH(self), maxcount
10066 );
10067 case PyUnicode_4BYTE_KIND:
10068 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010069 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 PyUnicode_GET_LENGTH(self), maxcount
10071 );
10072 default:
10073 assert(0);
10074 return NULL;
10075 }
10076
10077 if (PyUnicode_READY(substring) == -1)
10078 return NULL;
10079
10080 kind1 = PyUnicode_KIND(self);
10081 kind2 = PyUnicode_KIND(substring);
10082 kind = kind1 > kind2 ? kind1 : kind2;
10083 buf1 = PyUnicode_DATA(self);
10084 buf2 = PyUnicode_DATA(substring);
10085 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010086 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (!buf1)
10088 return NULL;
10089 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010090 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 if (!buf2) {
10092 if (kind1 != kind) PyMem_Free(buf1);
10093 return NULL;
10094 }
10095 len1 = PyUnicode_GET_LENGTH(self);
10096 len2 = PyUnicode_GET_LENGTH(substring);
10097
Benjamin Petersonead6b532011-12-20 17:23:42 -060010098 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010100 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10101 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010102 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 else
10104 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010105 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 break;
10107 case PyUnicode_2BYTE_KIND:
10108 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010109 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 break;
10111 case PyUnicode_4BYTE_KIND:
10112 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010113 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 break;
10115 default:
10116 out = NULL;
10117 }
10118 if (kind1 != kind)
10119 PyMem_Free(buf1);
10120 if (kind2 != kind)
10121 PyMem_Free(buf2);
10122 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010123}
10124
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010126rsplit(PyObject *self,
10127 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010128 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010129{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 int kind1, kind2, kind;
10131 void *buf1, *buf2;
10132 Py_ssize_t len1, len2;
10133 PyObject* out;
10134
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010135 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010136 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (PyUnicode_READY(self) == -1)
10139 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010142 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 if (PyUnicode_IS_ASCII(self))
10145 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010146 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010147 PyUnicode_GET_LENGTH(self), maxcount
10148 );
10149 else
10150 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010151 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010152 PyUnicode_GET_LENGTH(self), maxcount
10153 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 case PyUnicode_2BYTE_KIND:
10155 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010156 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyUnicode_GET_LENGTH(self), maxcount
10158 );
10159 case PyUnicode_4BYTE_KIND:
10160 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 PyUnicode_GET_LENGTH(self), maxcount
10163 );
10164 default:
10165 assert(0);
10166 return NULL;
10167 }
10168
10169 if (PyUnicode_READY(substring) == -1)
10170 return NULL;
10171
10172 kind1 = PyUnicode_KIND(self);
10173 kind2 = PyUnicode_KIND(substring);
10174 kind = kind1 > kind2 ? kind1 : kind2;
10175 buf1 = PyUnicode_DATA(self);
10176 buf2 = PyUnicode_DATA(substring);
10177 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010178 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 if (!buf1)
10180 return NULL;
10181 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 if (!buf2) {
10184 if (kind1 != kind) PyMem_Free(buf1);
10185 return NULL;
10186 }
10187 len1 = PyUnicode_GET_LENGTH(self);
10188 len2 = PyUnicode_GET_LENGTH(substring);
10189
Benjamin Petersonead6b532011-12-20 17:23:42 -060010190 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10193 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010194 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010195 else
10196 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 break;
10199 case PyUnicode_2BYTE_KIND:
10200 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010201 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 break;
10203 case PyUnicode_4BYTE_KIND:
10204 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010205 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 break;
10207 default:
10208 out = NULL;
10209 }
10210 if (kind1 != kind)
10211 PyMem_Free(buf1);
10212 if (kind2 != kind)
10213 PyMem_Free(buf2);
10214 return out;
10215}
10216
10217static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10219 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010221 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010223 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10224 return asciilib_find(buf1, len1, buf2, len2, offset);
10225 else
10226 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 case PyUnicode_2BYTE_KIND:
10228 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10229 case PyUnicode_4BYTE_KIND:
10230 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10231 }
10232 assert(0);
10233 return -1;
10234}
10235
10236static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010237anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10238 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010240 switch (kind) {
10241 case PyUnicode_1BYTE_KIND:
10242 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10243 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10244 else
10245 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10246 case PyUnicode_2BYTE_KIND:
10247 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10248 case PyUnicode_4BYTE_KIND:
10249 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10250 }
10251 assert(0);
10252 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010253}
10254
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010255static void
10256replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10257 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10258{
10259 int kind = PyUnicode_KIND(u);
10260 void *data = PyUnicode_DATA(u);
10261 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10262 if (kind == PyUnicode_1BYTE_KIND) {
10263 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10264 (Py_UCS1 *)data + len,
10265 u1, u2, maxcount);
10266 }
10267 else if (kind == PyUnicode_2BYTE_KIND) {
10268 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10269 (Py_UCS2 *)data + len,
10270 u1, u2, maxcount);
10271 }
10272 else {
10273 assert(kind == PyUnicode_4BYTE_KIND);
10274 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10275 (Py_UCS4 *)data + len,
10276 u1, u2, maxcount);
10277 }
10278}
10279
Alexander Belopolsky40018472011-02-26 01:02:56 +000010280static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281replace(PyObject *self, PyObject *str1,
10282 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 PyObject *u;
10285 char *sbuf = PyUnicode_DATA(self);
10286 char *buf1 = PyUnicode_DATA(str1);
10287 char *buf2 = PyUnicode_DATA(str2);
10288 int srelease = 0, release1 = 0, release2 = 0;
10289 int skind = PyUnicode_KIND(self);
10290 int kind1 = PyUnicode_KIND(str1);
10291 int kind2 = PyUnicode_KIND(str2);
10292 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10293 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10294 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010295 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010296 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297
10298 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010299 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010301 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302
Victor Stinner59de0ee2011-10-07 10:01:28 +020010303 if (str1 == str2)
10304 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305
Victor Stinner49a0a212011-10-12 23:46:10 +020010306 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010307 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10308 if (maxchar < maxchar_str1)
10309 /* substring too wide to be present */
10310 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010311 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10312 /* Replacing str1 with str2 may cause a maxchar reduction in the
10313 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010314 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010315 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010318 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010320 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010322 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010323 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010324 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010325
Victor Stinner69ed0f42013-04-09 21:48:24 +020010326 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010327 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010328 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010330 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010332 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010334
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010335 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10336 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010337 }
10338 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 int rkind = skind;
10340 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010341 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 if (kind1 < rkind) {
10344 /* widen substring */
10345 buf1 = _PyUnicode_AsKind(str1, rkind);
10346 if (!buf1) goto error;
10347 release1 = 1;
10348 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010349 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010350 if (i < 0)
10351 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 if (rkind > kind2) {
10353 /* widen replacement */
10354 buf2 = _PyUnicode_AsKind(str2, rkind);
10355 if (!buf2) goto error;
10356 release2 = 1;
10357 }
10358 else if (rkind < kind2) {
10359 /* widen self and buf1 */
10360 rkind = kind2;
10361 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010362 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 sbuf = _PyUnicode_AsKind(self, rkind);
10364 if (!sbuf) goto error;
10365 srelease = 1;
10366 buf1 = _PyUnicode_AsKind(str1, rkind);
10367 if (!buf1) goto error;
10368 release1 = 1;
10369 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010370 u = PyUnicode_New(slen, maxchar);
10371 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010373 assert(PyUnicode_KIND(u) == rkind);
10374 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010375
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010377 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010378 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010380 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010382
10383 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010384 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010385 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010386 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010387 if (i == -1)
10388 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010391 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010393 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010395 }
10396 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010398 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 int rkind = skind;
10400 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010401
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010403 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 buf1 = _PyUnicode_AsKind(str1, rkind);
10405 if (!buf1) goto error;
10406 release1 = 1;
10407 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010408 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010409 if (n == 0)
10410 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010412 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 buf2 = _PyUnicode_AsKind(str2, rkind);
10414 if (!buf2) goto error;
10415 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010416 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010418 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 rkind = kind2;
10420 sbuf = _PyUnicode_AsKind(self, rkind);
10421 if (!sbuf) goto error;
10422 srelease = 1;
10423 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010424 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 buf1 = _PyUnicode_AsKind(str1, rkind);
10426 if (!buf1) goto error;
10427 release1 = 1;
10428 }
10429 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10430 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010431 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 PyErr_SetString(PyExc_OverflowError,
10433 "replace string is too long");
10434 goto error;
10435 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010436 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010437 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010438 _Py_INCREF_UNICODE_EMPTY();
10439 if (!unicode_empty)
10440 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010441 u = unicode_empty;
10442 goto done;
10443 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010444 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 PyErr_SetString(PyExc_OverflowError,
10446 "replace string is too long");
10447 goto error;
10448 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010449 u = PyUnicode_New(new_size, maxchar);
10450 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010452 assert(PyUnicode_KIND(u) == rkind);
10453 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 ires = i = 0;
10455 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 while (n-- > 0) {
10457 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010458 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010459 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010460 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010461 if (j == -1)
10462 break;
10463 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010464 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010465 memcpy(res + rkind * ires,
10466 sbuf + rkind * i,
10467 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010469 }
10470 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010472 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010474 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010480 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010481 memcpy(res + rkind * ires,
10482 sbuf + rkind * i,
10483 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010484 }
10485 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010486 /* interleave */
10487 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010488 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010490 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010492 if (--n <= 0)
10493 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010494 memcpy(res + rkind * ires,
10495 sbuf + rkind * i,
10496 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 ires++;
10498 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010499 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010500 memcpy(res + rkind * ires,
10501 sbuf + rkind * i,
10502 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010503 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 }
10505
10506 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010507 unicode_adjust_maxchar(&u);
10508 if (u == NULL)
10509 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010511
10512 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 if (srelease)
10514 PyMem_FREE(sbuf);
10515 if (release1)
10516 PyMem_FREE(buf1);
10517 if (release2)
10518 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010519 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521
Benjamin Peterson29060642009-01-31 22:14:21 +000010522 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010523 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (srelease)
10525 PyMem_FREE(sbuf);
10526 if (release1)
10527 PyMem_FREE(buf1);
10528 if (release2)
10529 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010530 return unicode_result_unchanged(self);
10531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 error:
10533 if (srelease && sbuf)
10534 PyMem_FREE(sbuf);
10535 if (release1 && buf1)
10536 PyMem_FREE(buf1);
10537 if (release2 && buf2)
10538 PyMem_FREE(buf2);
10539 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540}
10541
10542/* --- Unicode Object Methods --------------------------------------------- */
10543
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010544PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010545 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546\n\
10547Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010548characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549
10550static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010551unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010553 if (PyUnicode_READY(self) == -1)
10554 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010555 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556}
10557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010558PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010559 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560\n\
10561Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010562have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563
10564static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010565unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010567 if (PyUnicode_READY(self) == -1)
10568 return NULL;
10569 if (PyUnicode_GET_LENGTH(self) == 0)
10570 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010571 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572}
10573
Benjamin Petersond5890c82012-01-14 13:23:30 -050010574PyDoc_STRVAR(casefold__doc__,
10575 "S.casefold() -> str\n\
10576\n\
10577Return a version of S suitable for caseless comparisons.");
10578
10579static PyObject *
10580unicode_casefold(PyObject *self)
10581{
10582 if (PyUnicode_READY(self) == -1)
10583 return NULL;
10584 if (PyUnicode_IS_ASCII(self))
10585 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010586 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010587}
10588
10589
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010590/* Argument converter. Coerces to a single unicode character */
10591
10592static int
10593convert_uc(PyObject *obj, void *addr)
10594{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010596 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010597
Benjamin Peterson14339b62009-01-31 16:36:08 +000010598 uniobj = PyUnicode_FromObject(obj);
10599 if (uniobj == NULL) {
10600 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010601 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010602 return 0;
10603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010605 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010606 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010607 Py_DECREF(uniobj);
10608 return 0;
10609 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010611 Py_DECREF(uniobj);
10612 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010613}
10614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010615PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010616 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010618Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010619done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620
10621static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010622unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010624 Py_ssize_t marg, left;
10625 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 Py_UCS4 fillchar = ' ';
10627
Victor Stinnere9a29352011-10-01 02:14:59 +020010628 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630
Benjamin Petersonbac79492012-01-14 13:34:47 -050010631 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632 return NULL;
10633
Victor Stinnerc4b49542011-12-11 22:44:26 +010010634 if (PyUnicode_GET_LENGTH(self) >= width)
10635 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636
Victor Stinnerc4b49542011-12-11 22:44:26 +010010637 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638 left = marg / 2 + (marg & width & 1);
10639
Victor Stinner9310abb2011-10-05 00:59:23 +020010640 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641}
10642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643/* This function assumes that str1 and str2 are readied by the caller. */
10644
Marc-André Lemburge5034372000-08-08 08:04:29 +000010645static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010646unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010647{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010648#define COMPARE(TYPE1, TYPE2) \
10649 do { \
10650 TYPE1* p1 = (TYPE1 *)data1; \
10651 TYPE2* p2 = (TYPE2 *)data2; \
10652 TYPE1* end = p1 + len; \
10653 Py_UCS4 c1, c2; \
10654 for (; p1 != end; p1++, p2++) { \
10655 c1 = *p1; \
10656 c2 = *p2; \
10657 if (c1 != c2) \
10658 return (c1 < c2) ? -1 : 1; \
10659 } \
10660 } \
10661 while (0)
10662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 int kind1, kind2;
10664 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010665 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010667 kind1 = PyUnicode_KIND(str1);
10668 kind2 = PyUnicode_KIND(str2);
10669 data1 = PyUnicode_DATA(str1);
10670 data2 = PyUnicode_DATA(str2);
10671 len1 = PyUnicode_GET_LENGTH(str1);
10672 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010673 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010674
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010675 switch(kind1) {
10676 case PyUnicode_1BYTE_KIND:
10677 {
10678 switch(kind2) {
10679 case PyUnicode_1BYTE_KIND:
10680 {
10681 int cmp = memcmp(data1, data2, len);
10682 /* normalize result of memcmp() into the range [-1; 1] */
10683 if (cmp < 0)
10684 return -1;
10685 if (cmp > 0)
10686 return 1;
10687 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010688 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010689 case PyUnicode_2BYTE_KIND:
10690 COMPARE(Py_UCS1, Py_UCS2);
10691 break;
10692 case PyUnicode_4BYTE_KIND:
10693 COMPARE(Py_UCS1, Py_UCS4);
10694 break;
10695 default:
10696 assert(0);
10697 }
10698 break;
10699 }
10700 case PyUnicode_2BYTE_KIND:
10701 {
10702 switch(kind2) {
10703 case PyUnicode_1BYTE_KIND:
10704 COMPARE(Py_UCS2, Py_UCS1);
10705 break;
10706 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010707 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010708 COMPARE(Py_UCS2, Py_UCS2);
10709 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010710 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010711 case PyUnicode_4BYTE_KIND:
10712 COMPARE(Py_UCS2, Py_UCS4);
10713 break;
10714 default:
10715 assert(0);
10716 }
10717 break;
10718 }
10719 case PyUnicode_4BYTE_KIND:
10720 {
10721 switch(kind2) {
10722 case PyUnicode_1BYTE_KIND:
10723 COMPARE(Py_UCS4, Py_UCS1);
10724 break;
10725 case PyUnicode_2BYTE_KIND:
10726 COMPARE(Py_UCS4, Py_UCS2);
10727 break;
10728 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010729 {
10730#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10731 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10732 /* normalize result of wmemcmp() into the range [-1; 1] */
10733 if (cmp < 0)
10734 return -1;
10735 if (cmp > 0)
10736 return 1;
10737#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010738 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010739#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010740 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010741 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010742 default:
10743 assert(0);
10744 }
10745 break;
10746 }
10747 default:
10748 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010749 }
10750
Victor Stinner770e19e2012-10-04 22:59:45 +020010751 if (len1 == len2)
10752 return 0;
10753 if (len1 < len2)
10754 return -1;
10755 else
10756 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010757
10758#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010759}
10760
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010761Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010762unicode_compare_eq(PyObject *str1, PyObject *str2)
10763{
10764 int kind;
10765 void *data1, *data2;
10766 Py_ssize_t len;
10767 int cmp;
10768
Victor Stinnere5567ad2012-10-23 02:48:49 +020010769 len = PyUnicode_GET_LENGTH(str1);
10770 if (PyUnicode_GET_LENGTH(str2) != len)
10771 return 0;
10772 kind = PyUnicode_KIND(str1);
10773 if (PyUnicode_KIND(str2) != kind)
10774 return 0;
10775 data1 = PyUnicode_DATA(str1);
10776 data2 = PyUnicode_DATA(str2);
10777
10778 cmp = memcmp(data1, data2, len * kind);
10779 return (cmp == 0);
10780}
10781
10782
Alexander Belopolsky40018472011-02-26 01:02:56 +000010783int
10784PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10787 if (PyUnicode_READY(left) == -1 ||
10788 PyUnicode_READY(right) == -1)
10789 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010790
10791 /* a string is equal to itself */
10792 if (left == right)
10793 return 0;
10794
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010795 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010797 PyErr_Format(PyExc_TypeError,
10798 "Can't compare %.100s and %.100s",
10799 left->ob_type->tp_name,
10800 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801 return -1;
10802}
10803
Martin v. Löwis5b222132007-06-10 09:51:05 +000010804int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010805_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10806{
10807 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10808 if (right_str == NULL)
10809 return -1;
10810 return PyUnicode_Compare(left, right_str);
10811}
10812
10813int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010814PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10815{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 Py_ssize_t i;
10817 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 Py_UCS4 chr;
10819
Victor Stinner910337b2011-10-03 03:20:16 +020010820 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821 if (PyUnicode_READY(uni) == -1)
10822 return -1;
10823 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010824 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010825 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010826 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010827 size_t len, len2 = strlen(str);
10828 int cmp;
10829
10830 len = Py_MIN(len1, len2);
10831 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010832 if (cmp != 0) {
10833 if (cmp < 0)
10834 return -1;
10835 else
10836 return 1;
10837 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010838 if (len1 > len2)
10839 return 1; /* uni is longer */
10840 if (len2 > len1)
10841 return -1; /* str is longer */
10842 return 0;
10843 }
10844 else {
10845 void *data = PyUnicode_DATA(uni);
10846 /* Compare Unicode string and source character set string */
10847 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10848 if (chr != str[i])
10849 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10850 /* This check keeps Python strings that end in '\0' from comparing equal
10851 to C strings identical up to that point. */
10852 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10853 return 1; /* uni is longer */
10854 if (str[i])
10855 return -1; /* str is longer */
10856 return 0;
10857 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010858}
10859
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010860
Benjamin Peterson29060642009-01-31 22:14:21 +000010861#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010862 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010863
Alexander Belopolsky40018472011-02-26 01:02:56 +000010864PyObject *
10865PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010866{
10867 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010868 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010869
Victor Stinnere5567ad2012-10-23 02:48:49 +020010870 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10871 Py_RETURN_NOTIMPLEMENTED;
10872
10873 if (PyUnicode_READY(left) == -1 ||
10874 PyUnicode_READY(right) == -1)
10875 return NULL;
10876
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010877 if (left == right) {
10878 switch (op) {
10879 case Py_EQ:
10880 case Py_LE:
10881 case Py_GE:
10882 /* a string is equal to itself */
10883 v = Py_True;
10884 break;
10885 case Py_NE:
10886 case Py_LT:
10887 case Py_GT:
10888 v = Py_False;
10889 break;
10890 default:
10891 PyErr_BadArgument();
10892 return NULL;
10893 }
10894 }
10895 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010896 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010897 result ^= (op == Py_NE);
10898 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010899 }
10900 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010901 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010902
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010903 /* Convert the return value to a Boolean */
10904 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010905 case Py_LE:
10906 v = TEST_COND(result <= 0);
10907 break;
10908 case Py_GE:
10909 v = TEST_COND(result >= 0);
10910 break;
10911 case Py_LT:
10912 v = TEST_COND(result == -1);
10913 break;
10914 case Py_GT:
10915 v = TEST_COND(result == 1);
10916 break;
10917 default:
10918 PyErr_BadArgument();
10919 return NULL;
10920 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010921 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010922 Py_INCREF(v);
10923 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010924}
10925
Alexander Belopolsky40018472011-02-26 01:02:56 +000010926int
10927PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010928{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010929 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010930 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 void *buf1, *buf2;
10932 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010933 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010934
10935 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010936 sub = PyUnicode_FromObject(element);
10937 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010938 PyErr_Format(PyExc_TypeError,
10939 "'in <string>' requires string as left operand, not %s",
10940 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010941 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010942 }
10943
Thomas Wouters477c8d52006-05-27 19:21:47 +000010944 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010945 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010946 Py_DECREF(sub);
10947 return -1;
10948 }
10949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 kind1 = PyUnicode_KIND(str);
10951 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 buf1 = PyUnicode_DATA(str);
10953 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010954 if (kind2 != kind1) {
10955 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010956 Py_DECREF(sub);
10957 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010958 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010959 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010960 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 if (!buf2) {
10963 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010964 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010965 return -1;
10966 }
10967 len1 = PyUnicode_GET_LENGTH(str);
10968 len2 = PyUnicode_GET_LENGTH(sub);
10969
Victor Stinner77282cb2013-04-14 19:22:47 +020010970 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010971 case PyUnicode_1BYTE_KIND:
10972 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10973 break;
10974 case PyUnicode_2BYTE_KIND:
10975 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10976 break;
10977 case PyUnicode_4BYTE_KIND:
10978 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10979 break;
10980 default:
10981 result = -1;
10982 assert(0);
10983 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010984
10985 Py_DECREF(str);
10986 Py_DECREF(sub);
10987
Victor Stinner77282cb2013-04-14 19:22:47 +020010988 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010989 PyMem_Free(buf2);
10990
Guido van Rossum403d68b2000-03-13 15:55:09 +000010991 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010992}
10993
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994/* Concat to string or Unicode object giving a new Unicode object. */
10995
Alexander Belopolsky40018472011-02-26 01:02:56 +000010996PyObject *
10997PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010999 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011000 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011001 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002
11003 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011004 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011006 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011009 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010
11011 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011012 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011014 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011016 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011017 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011018 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 }
11020
Victor Stinner488fa492011-12-12 00:01:39 +010011021 u_len = PyUnicode_GET_LENGTH(u);
11022 v_len = PyUnicode_GET_LENGTH(v);
11023 if (u_len > PY_SSIZE_T_MAX - v_len) {
11024 PyErr_SetString(PyExc_OverflowError,
11025 "strings are too large to concat");
11026 goto onError;
11027 }
11028 new_len = u_len + v_len;
11029
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011030 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011031 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011032 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011035 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011038 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11039 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040 Py_DECREF(u);
11041 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011042 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Benjamin Peterson29060642009-01-31 22:14:21 +000011045 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046 Py_XDECREF(u);
11047 Py_XDECREF(v);
11048 return NULL;
11049}
11050
Walter Dörwald1ab83302007-05-18 17:15:44 +000011051void
Victor Stinner23e56682011-10-03 03:54:37 +020011052PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011053{
Victor Stinner23e56682011-10-03 03:54:37 +020011054 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011055 Py_UCS4 maxchar, maxchar2;
11056 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011057
11058 if (p_left == NULL) {
11059 if (!PyErr_Occurred())
11060 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011061 return;
11062 }
Victor Stinner23e56682011-10-03 03:54:37 +020011063 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011064 if (right == NULL || left == NULL
11065 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011066 if (!PyErr_Occurred())
11067 PyErr_BadInternalCall();
11068 goto error;
11069 }
11070
Benjamin Petersonbac79492012-01-14 13:34:47 -050011071 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011072 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011073 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011074 goto error;
11075
Victor Stinner488fa492011-12-12 00:01:39 +010011076 /* Shortcuts */
11077 if (left == unicode_empty) {
11078 Py_DECREF(left);
11079 Py_INCREF(right);
11080 *p_left = right;
11081 return;
11082 }
11083 if (right == unicode_empty)
11084 return;
11085
11086 left_len = PyUnicode_GET_LENGTH(left);
11087 right_len = PyUnicode_GET_LENGTH(right);
11088 if (left_len > PY_SSIZE_T_MAX - right_len) {
11089 PyErr_SetString(PyExc_OverflowError,
11090 "strings are too large to concat");
11091 goto error;
11092 }
11093 new_len = left_len + right_len;
11094
11095 if (unicode_modifiable(left)
11096 && PyUnicode_CheckExact(right)
11097 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011098 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11099 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011100 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011101 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011102 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11103 {
11104 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011105 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011106 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011107
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011108 /* copy 'right' into the newly allocated area of 'left' */
11109 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011110 }
Victor Stinner488fa492011-12-12 00:01:39 +010011111 else {
11112 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11113 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011114 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011115
Victor Stinner488fa492011-12-12 00:01:39 +010011116 /* Concat the two Unicode strings */
11117 res = PyUnicode_New(new_len, maxchar);
11118 if (res == NULL)
11119 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011120 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11121 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011122 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011123 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011124 }
11125 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011126 return;
11127
11128error:
Victor Stinner488fa492011-12-12 00:01:39 +010011129 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011130}
11131
11132void
11133PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11134{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011135 PyUnicode_Append(pleft, right);
11136 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011137}
11138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011139PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011140 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011142Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011143string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011144interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145
11146static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011147unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011149 PyObject *substring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011150 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011151 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011152 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153 int kind1, kind2, kind;
11154 void *buf1, *buf2;
11155 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156
Jesus Ceaac451502011-04-20 17:09:23 +020011157 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11158 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011159 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011161 kind1 = PyUnicode_KIND(self);
11162 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011163 if (kind2 > kind1) {
11164 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011165 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011166 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011167 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 buf1 = PyUnicode_DATA(self);
11169 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011171 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 if (!buf2) {
11173 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 return NULL;
11175 }
11176 len1 = PyUnicode_GET_LENGTH(self);
11177 len2 = PyUnicode_GET_LENGTH(substring);
11178
11179 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011180 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181 case PyUnicode_1BYTE_KIND:
11182 iresult = ucs1lib_count(
11183 ((Py_UCS1*)buf1) + start, end - start,
11184 buf2, len2, PY_SSIZE_T_MAX
11185 );
11186 break;
11187 case PyUnicode_2BYTE_KIND:
11188 iresult = ucs2lib_count(
11189 ((Py_UCS2*)buf1) + start, end - start,
11190 buf2, len2, PY_SSIZE_T_MAX
11191 );
11192 break;
11193 case PyUnicode_4BYTE_KIND:
11194 iresult = ucs4lib_count(
11195 ((Py_UCS4*)buf1) + start, end - start,
11196 buf2, len2, PY_SSIZE_T_MAX
11197 );
11198 break;
11199 default:
11200 assert(0); iresult = 0;
11201 }
11202
11203 result = PyLong_FromSsize_t(iresult);
11204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 if (kind2 != kind)
11206 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011209
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210 return result;
11211}
11212
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011213PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011214 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011216Encode S using the codec registered for encoding. Default encoding\n\
11217is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011218handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011219a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11220'xmlcharrefreplace' as well as any other name registered with\n\
11221codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222
11223static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011224unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011226 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227 char *encoding = NULL;
11228 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011229
Benjamin Peterson308d6372009-09-18 21:42:35 +000011230 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11231 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011233 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011234}
11235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011236PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011237 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238\n\
11239Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011240If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241
11242static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011243unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011245 Py_ssize_t i, j, line_pos, src_len, incr;
11246 Py_UCS4 ch;
11247 PyObject *u;
11248 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011249 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011251 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011252 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253
Ezio Melotti745d54d2013-11-16 19:10:57 +020011254 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11255 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011256 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257
Antoine Pitrou22425222011-10-04 19:10:51 +020011258 if (PyUnicode_READY(self) == -1)
11259 return NULL;
11260
Thomas Wouters7e474022000-07-16 12:04:32 +000011261 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011262 src_len = PyUnicode_GET_LENGTH(self);
11263 i = j = line_pos = 0;
11264 kind = PyUnicode_KIND(self);
11265 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011266 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011267 for (; i < src_len; i++) {
11268 ch = PyUnicode_READ(kind, src_data, i);
11269 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011270 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011271 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011272 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011274 goto overflow;
11275 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011276 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011277 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011280 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011281 goto overflow;
11282 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 if (ch == '\n' || ch == '\r')
11285 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011287 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011288 if (!found)
11289 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011290
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293 if (!u)
11294 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296
Antoine Pitroue71d5742011-10-04 15:55:09 +020011297 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
Antoine Pitroue71d5742011-10-04 15:55:09 +020011299 for (; i < src_len; i++) {
11300 ch = PyUnicode_READ(kind, src_data, i);
11301 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011302 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011303 incr = tabsize - (line_pos % tabsize);
11304 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011305 FILL(kind, dest_data, ' ', j, incr);
11306 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011307 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011308 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011309 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011310 line_pos++;
11311 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011312 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011313 if (ch == '\n' || ch == '\r')
11314 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011316 }
11317 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011318 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011319
Antoine Pitroue71d5742011-10-04 15:55:09 +020011320 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011321 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11322 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323}
11324
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011325PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327\n\
11328Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011329such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330arguments start and end are interpreted as in slice notation.\n\
11331\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011333
11334static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011337 PyObject *substring = NULL;
11338 Py_ssize_t start = 0;
11339 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011340 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341
Jesus Ceaac451502011-04-20 17:09:23 +020011342 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11343 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345
Christian Heimesd47802e2013-06-29 21:33:36 +020011346 if (PyUnicode_READY(self) == -1) {
11347 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011349 }
11350 if (PyUnicode_READY(substring) == -1) {
11351 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354
Victor Stinner7931d9a2011-11-04 00:22:48 +010011355 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356
11357 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011359 if (result == -2)
11360 return NULL;
11361
Christian Heimes217cfd12007-12-02 14:31:20 +000011362 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363}
11364
11365static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011366unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011368 void *data;
11369 enum PyUnicode_Kind kind;
11370 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011371
11372 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11373 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011375 }
11376 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11377 PyErr_SetString(PyExc_IndexError, "string index out of range");
11378 return NULL;
11379 }
11380 kind = PyUnicode_KIND(self);
11381 data = PyUnicode_DATA(self);
11382 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011383 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384}
11385
Guido van Rossumc2504932007-09-18 19:42:40 +000011386/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011387 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011388static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011389unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390{
Guido van Rossumc2504932007-09-18 19:42:40 +000011391 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011392 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011393
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011394#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011395 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011396#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 if (_PyUnicode_HASH(self) != -1)
11398 return _PyUnicode_HASH(self);
11399 if (PyUnicode_READY(self) == -1)
11400 return -1;
11401 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011402 /*
11403 We make the hash of the empty string be 0, rather than using
11404 (prefix ^ suffix), since this slightly obfuscates the hash secret
11405 */
11406 if (len == 0) {
11407 _PyUnicode_HASH(self) = 0;
11408 return 0;
11409 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011410 x = _Py_HashBytes(PyUnicode_DATA(self),
11411 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011413 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414}
11415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
11421static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011424 Py_ssize_t result;
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020011425 PyObject *substring = NULL;
11426 Py_ssize_t start = 0;
11427 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428
Jesus Ceaac451502011-04-20 17:09:23 +020011429 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11430 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
Christian Heimesd47a0452013-06-29 21:21:37 +020011433 if (PyUnicode_READY(self) == -1) {
11434 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011436 }
11437 if (PyUnicode_READY(substring) == -1) {
11438 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441
Victor Stinner7931d9a2011-11-04 00:22:48 +010011442 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
11444 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (result == -2)
11447 return NULL;
11448
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 if (result < 0) {
11450 PyErr_SetString(PyExc_ValueError, "substring not found");
11451 return NULL;
11452 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011453
Christian Heimes217cfd12007-12-02 14:31:20 +000011454 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455}
11456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011457PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011460Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
11463static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011464unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 Py_ssize_t i, length;
11467 int kind;
11468 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469 int cased;
11470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (PyUnicode_READY(self) == -1)
11472 return NULL;
11473 length = PyUnicode_GET_LENGTH(self);
11474 kind = PyUnicode_KIND(self);
11475 data = PyUnicode_DATA(self);
11476
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (length == 1)
11479 return PyBool_FromLong(
11480 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011482 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011483 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011485
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 for (i = 0; i < length; i++) {
11488 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011489
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11491 return PyBool_FromLong(0);
11492 else if (!cased && Py_UNICODE_ISLOWER(ch))
11493 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011495 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496}
11497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011498PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011501Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011502at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
11504static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011505unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 Py_ssize_t i, length;
11508 int kind;
11509 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510 int cased;
11511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (PyUnicode_READY(self) == -1)
11513 return NULL;
11514 length = PyUnicode_GET_LENGTH(self);
11515 kind = PyUnicode_KIND(self);
11516 data = PyUnicode_DATA(self);
11517
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011519 if (length == 1)
11520 return PyBool_FromLong(
11521 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011523 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011526
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 for (i = 0; i < length; i++) {
11529 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011530
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11532 return PyBool_FromLong(0);
11533 else if (!cased && Py_UNICODE_ISUPPER(ch))
11534 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011536 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011539PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011542Return True if S is a titlecased string and there is at least one\n\
11543character in S, i.e. upper- and titlecase characters may only\n\
11544follow uncased characters and lowercase characters only cased ones.\n\
11545Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546
11547static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011548unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 Py_ssize_t i, length;
11551 int kind;
11552 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 int cased, previous_is_cased;
11554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 if (PyUnicode_READY(self) == -1)
11556 return NULL;
11557 length = PyUnicode_GET_LENGTH(self);
11558 kind = PyUnicode_KIND(self);
11559 data = PyUnicode_DATA(self);
11560
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 if (length == 1) {
11563 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11564 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11565 (Py_UNICODE_ISUPPER(ch) != 0));
11566 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011568 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011569 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011570 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011571
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 cased = 0;
11573 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011574 for (i = 0; i < length; i++) {
11575 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011576
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11578 if (previous_is_cased)
11579 return PyBool_FromLong(0);
11580 previous_is_cased = 1;
11581 cased = 1;
11582 }
11583 else if (Py_UNICODE_ISLOWER(ch)) {
11584 if (!previous_is_cased)
11585 return PyBool_FromLong(0);
11586 previous_is_cased = 1;
11587 cased = 1;
11588 }
11589 else
11590 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011592 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593}
11594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011595PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011596 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011598Return True if all characters in S are whitespace\n\
11599and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600
11601static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011602unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 Py_ssize_t i, length;
11605 int kind;
11606 void *data;
11607
11608 if (PyUnicode_READY(self) == -1)
11609 return NULL;
11610 length = PyUnicode_GET_LENGTH(self);
11611 kind = PyUnicode_KIND(self);
11612 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 if (length == 1)
11616 return PyBool_FromLong(
11617 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011619 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 for (i = 0; i < length; i++) {
11624 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011625 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011628 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011629}
11630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011631PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011632 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011633\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011634Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011635and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636
11637static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011638unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011639{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640 Py_ssize_t i, length;
11641 int kind;
11642 void *data;
11643
11644 if (PyUnicode_READY(self) == -1)
11645 return NULL;
11646 length = PyUnicode_GET_LENGTH(self);
11647 kind = PyUnicode_KIND(self);
11648 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011650 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 if (length == 1)
11652 return PyBool_FromLong(
11653 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011654
11655 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011657 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 for (i = 0; i < length; i++) {
11660 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011662 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011663 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011664}
11665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011666PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011667 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011668\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011669Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011670and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011671
11672static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011673unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011674{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 int kind;
11676 void *data;
11677 Py_ssize_t len, i;
11678
11679 if (PyUnicode_READY(self) == -1)
11680 return NULL;
11681
11682 kind = PyUnicode_KIND(self);
11683 data = PyUnicode_DATA(self);
11684 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011685
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011686 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 if (len == 1) {
11688 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11689 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11690 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011691
11692 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011695
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011696 for (i = 0; i < len; i++) {
11697 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011698 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011699 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011700 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011701 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011702}
11703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011704PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011705 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011707Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011708False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709
11710static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011711unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 Py_ssize_t i, length;
11714 int kind;
11715 void *data;
11716
11717 if (PyUnicode_READY(self) == -1)
11718 return NULL;
11719 length = PyUnicode_GET_LENGTH(self);
11720 kind = PyUnicode_KIND(self);
11721 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 if (length == 1)
11725 return PyBool_FromLong(
11726 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011728 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011730 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011732 for (i = 0; i < length; i++) {
11733 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011736 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737}
11738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011739PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011742Return True if all characters in S are digits\n\
11743and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744
11745static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011746unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 Py_ssize_t i, length;
11749 int kind;
11750 void *data;
11751
11752 if (PyUnicode_READY(self) == -1)
11753 return NULL;
11754 length = PyUnicode_GET_LENGTH(self);
11755 kind = PyUnicode_KIND(self);
11756 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 if (length == 1) {
11760 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11761 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11762 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011764 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 for (i = 0; i < length; i++) {
11769 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011770 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011772 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773}
11774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011775PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011776 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011778Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011779False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
11781static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011782unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 Py_ssize_t i, length;
11785 int kind;
11786 void *data;
11787
11788 if (PyUnicode_READY(self) == -1)
11789 return NULL;
11790 length = PyUnicode_GET_LENGTH(self);
11791 kind = PyUnicode_KIND(self);
11792 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793
Guido van Rossumd57fd912000-03-10 22:53:23 +000011794 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 if (length == 1)
11796 return PyBool_FromLong(
11797 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011799 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803 for (i = 0; i < length; i++) {
11804 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011805 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011807 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808}
11809
Martin v. Löwis47383402007-08-15 07:32:56 +000011810int
11811PyUnicode_IsIdentifier(PyObject *self)
11812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 int kind;
11814 void *data;
11815 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011816 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (PyUnicode_READY(self) == -1) {
11819 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011820 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 }
11822
11823 /* Special case for empty strings */
11824 if (PyUnicode_GET_LENGTH(self) == 0)
11825 return 0;
11826 kind = PyUnicode_KIND(self);
11827 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011828
11829 /* PEP 3131 says that the first character must be in
11830 XID_Start and subsequent characters in XID_Continue,
11831 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011832 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011833 letters, digits, underscore). However, given the current
11834 definition of XID_Start and XID_Continue, it is sufficient
11835 to check just for these, except that _ must be allowed
11836 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011838 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011839 return 0;
11840
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011841 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011843 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011844 return 1;
11845}
11846
11847PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011849\n\
11850Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011851to the language definition.\n\
11852\n\
11853Use keyword.iskeyword() to test for reserved identifiers\n\
11854such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011855
11856static PyObject*
11857unicode_isidentifier(PyObject *self)
11858{
11859 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11860}
11861
Georg Brandl559e5d72008-06-11 18:37:52 +000011862PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011864\n\
11865Return True if all characters in S are considered\n\
11866printable in repr() or S is empty, False otherwise.");
11867
11868static PyObject*
11869unicode_isprintable(PyObject *self)
11870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 Py_ssize_t i, length;
11872 int kind;
11873 void *data;
11874
11875 if (PyUnicode_READY(self) == -1)
11876 return NULL;
11877 length = PyUnicode_GET_LENGTH(self);
11878 kind = PyUnicode_KIND(self);
11879 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011880
11881 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011882 if (length == 1)
11883 return PyBool_FromLong(
11884 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 for (i = 0; i < length; i++) {
11887 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011888 Py_RETURN_FALSE;
11889 }
11890 }
11891 Py_RETURN_TRUE;
11892}
11893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011894PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011895 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896\n\
11897Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011898iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899
11900static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011901unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011903 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904}
11905
Martin v. Löwis18e16552006-02-15 17:27:45 +000011906static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011907unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 if (PyUnicode_READY(self) == -1)
11910 return -1;
11911 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912}
11913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011914PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011915 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011916\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011917Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011918done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919
11920static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011921unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011923 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 Py_UCS4 fillchar = ' ';
11925
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011926 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 return NULL;
11928
Benjamin Petersonbac79492012-01-14 13:34:47 -050011929 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011930 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931
Victor Stinnerc4b49542011-12-11 22:44:26 +010011932 if (PyUnicode_GET_LENGTH(self) >= width)
11933 return unicode_result_unchanged(self);
11934
11935 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011936}
11937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011938PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011941Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942
11943static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011944unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011946 if (PyUnicode_READY(self) == -1)
11947 return NULL;
11948 if (PyUnicode_IS_ASCII(self))
11949 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011950 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951}
11952
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953#define LEFTSTRIP 0
11954#define RIGHTSTRIP 1
11955#define BOTHSTRIP 2
11956
11957/* Arrays indexed by above */
11958static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11959
11960#define STRIPNAME(i) (stripformat[i]+3)
11961
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011962/* externally visible for str.strip(unicode) */
11963PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011964_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011965{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 void *data;
11967 int kind;
11968 Py_ssize_t i, j, len;
11969 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011970 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11973 return NULL;
11974
11975 kind = PyUnicode_KIND(self);
11976 data = PyUnicode_DATA(self);
11977 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011978 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11980 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011981 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011982
Benjamin Peterson14339b62009-01-31 16:36:08 +000011983 i = 0;
11984 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011985 while (i < len) {
11986 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11987 if (!BLOOM(sepmask, ch))
11988 break;
11989 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11990 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 i++;
11992 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011993 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011994
Benjamin Peterson14339b62009-01-31 16:36:08 +000011995 j = len;
11996 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011997 j--;
11998 while (j >= i) {
11999 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12000 if (!BLOOM(sepmask, ch))
12001 break;
12002 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12003 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012005 }
12006
Benjamin Peterson29060642009-01-31 22:14:21 +000012007 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012008 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012009
Victor Stinner7931d9a2011-11-04 00:22:48 +010012010 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011}
12012
12013PyObject*
12014PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12015{
12016 unsigned char *data;
12017 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012018 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019
Victor Stinnerde636f32011-10-01 03:55:54 +020012020 if (PyUnicode_READY(self) == -1)
12021 return NULL;
12022
Victor Stinner684d5fd2012-05-03 02:32:34 +020012023 length = PyUnicode_GET_LENGTH(self);
12024 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012025
Victor Stinner684d5fd2012-05-03 02:32:34 +020012026 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012027 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012028
Victor Stinnerde636f32011-10-01 03:55:54 +020012029 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012030 PyErr_SetString(PyExc_IndexError, "string index out of range");
12031 return NULL;
12032 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012033 if (start >= length || end < start)
12034 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012035
Victor Stinner684d5fd2012-05-03 02:32:34 +020012036 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012037 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012038 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012039 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012040 }
12041 else {
12042 kind = PyUnicode_KIND(self);
12043 data = PyUnicode_1BYTE_DATA(self);
12044 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012045 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012046 length);
12047 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049
12050static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012051do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 Py_ssize_t len, i, j;
12054
12055 if (PyUnicode_READY(self) == -1)
12056 return NULL;
12057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012059
Victor Stinnercc7af722013-04-09 22:39:24 +020012060 if (PyUnicode_IS_ASCII(self)) {
12061 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12062
12063 i = 0;
12064 if (striptype != RIGHTSTRIP) {
12065 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012066 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012067 if (!_Py_ascii_whitespace[ch])
12068 break;
12069 i++;
12070 }
12071 }
12072
12073 j = len;
12074 if (striptype != LEFTSTRIP) {
12075 j--;
12076 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012077 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012078 if (!_Py_ascii_whitespace[ch])
12079 break;
12080 j--;
12081 }
12082 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012083 }
12084 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012085 else {
12086 int kind = PyUnicode_KIND(self);
12087 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012088
Victor Stinnercc7af722013-04-09 22:39:24 +020012089 i = 0;
12090 if (striptype != RIGHTSTRIP) {
12091 while (i < len) {
12092 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12093 if (!Py_UNICODE_ISSPACE(ch))
12094 break;
12095 i++;
12096 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012097 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012098
12099 j = len;
12100 if (striptype != LEFTSTRIP) {
12101 j--;
12102 while (j >= i) {
12103 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12104 if (!Py_UNICODE_ISSPACE(ch))
12105 break;
12106 j--;
12107 }
12108 j++;
12109 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012110 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012111
Victor Stinner7931d9a2011-11-04 00:22:48 +010012112 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113}
12114
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012115
12116static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012117do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012118{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012119 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012120
Serhiy Storchakac6792272013-10-19 21:03:34 +030012121 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012122 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012123
Benjamin Peterson14339b62009-01-31 16:36:08 +000012124 if (sep != NULL && sep != Py_None) {
12125 if (PyUnicode_Check(sep))
12126 return _PyUnicode_XStrip(self, striptype, sep);
12127 else {
12128 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012129 "%s arg must be None or str",
12130 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012131 return NULL;
12132 }
12133 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134
Benjamin Peterson14339b62009-01-31 16:36:08 +000012135 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012136}
12137
12138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012139PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012141\n\
12142Return a copy of the string S with leading and trailing\n\
12143whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012144If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145
12146static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012147unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012149 if (PyTuple_GET_SIZE(args) == 0)
12150 return do_strip(self, BOTHSTRIP); /* Common case */
12151 else
12152 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012153}
12154
12155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012156PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012158\n\
12159Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012160If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161
12162static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012163unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012164{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012165 if (PyTuple_GET_SIZE(args) == 0)
12166 return do_strip(self, LEFTSTRIP); /* Common case */
12167 else
12168 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012169}
12170
12171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012172PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012173 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012174\n\
12175Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012176If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012177
12178static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012179unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012180{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012181 if (PyTuple_GET_SIZE(args) == 0)
12182 return do_strip(self, RIGHTSTRIP); /* Common case */
12183 else
12184 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012185}
12186
12187
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012189unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012190{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012191 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193
Serhiy Storchaka05997252013-01-26 12:14:02 +020012194 if (len < 1)
12195 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196
Victor Stinnerc4b49542011-12-11 22:44:26 +010012197 /* no repeat, return original string */
12198 if (len == 1)
12199 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012200
Benjamin Petersonbac79492012-01-14 13:34:47 -050012201 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 return NULL;
12203
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012204 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012205 PyErr_SetString(PyExc_OverflowError,
12206 "repeated string is too long");
12207 return NULL;
12208 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012210
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012211 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212 if (!u)
12213 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012214 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216 if (PyUnicode_GET_LENGTH(str) == 1) {
12217 const int kind = PyUnicode_KIND(str);
12218 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012219 if (kind == PyUnicode_1BYTE_KIND) {
12220 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012221 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012222 }
12223 else if (kind == PyUnicode_2BYTE_KIND) {
12224 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012225 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012226 ucs2[n] = fill_char;
12227 } else {
12228 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12229 assert(kind == PyUnicode_4BYTE_KIND);
12230 for (n = 0; n < len; ++n)
12231 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012232 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 }
12234 else {
12235 /* number of characters copied this far */
12236 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012237 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 char *to = (char *) PyUnicode_DATA(u);
12239 Py_MEMCPY(to, PyUnicode_DATA(str),
12240 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012241 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 n = (done <= nchars-done) ? done : nchars-done;
12243 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012244 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246 }
12247
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012248 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012249 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250}
12251
Alexander Belopolsky40018472011-02-26 01:02:56 +000012252PyObject *
12253PyUnicode_Replace(PyObject *obj,
12254 PyObject *subobj,
12255 PyObject *replobj,
12256 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257{
12258 PyObject *self;
12259 PyObject *str1;
12260 PyObject *str2;
12261 PyObject *result;
12262
12263 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012264 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012267 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012268 Py_DECREF(self);
12269 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270 }
12271 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012272 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012273 Py_DECREF(self);
12274 Py_DECREF(str1);
12275 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012277 if (PyUnicode_READY(self) == -1 ||
12278 PyUnicode_READY(str1) == -1 ||
12279 PyUnicode_READY(str2) == -1)
12280 result = NULL;
12281 else
12282 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283 Py_DECREF(self);
12284 Py_DECREF(str1);
12285 Py_DECREF(str2);
12286 return result;
12287}
12288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012289PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012290 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291\n\
12292Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012293old replaced by new. If the optional argument count is\n\
12294given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295
12296static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 PyObject *str1;
12300 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012301 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302 PyObject *result;
12303
Martin v. Löwis18e16552006-02-15 17:27:45 +000012304 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012306 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012307 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012309 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 return NULL;
12311 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012312 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012313 Py_DECREF(str1);
12314 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012315 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012316 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12317 result = NULL;
12318 else
12319 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320
12321 Py_DECREF(str1);
12322 Py_DECREF(str2);
12323 return result;
12324}
12325
Alexander Belopolsky40018472011-02-26 01:02:56 +000012326static PyObject *
12327unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012329 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 Py_ssize_t isize;
12331 Py_ssize_t osize, squote, dquote, i, o;
12332 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012333 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012337 return NULL;
12338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 isize = PyUnicode_GET_LENGTH(unicode);
12340 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 /* Compute length of output, quote characters, and
12343 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012344 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 max = 127;
12346 squote = dquote = 0;
12347 ikind = PyUnicode_KIND(unicode);
12348 for (i = 0; i < isize; i++) {
12349 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012350 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012352 case '\'': squote++; break;
12353 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012355 incr = 2;
12356 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 default:
12358 /* Fast-path ASCII */
12359 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012360 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012362 ;
12363 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012364 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012366 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012368 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012370 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012372 if (osize > PY_SSIZE_T_MAX - incr) {
12373 PyErr_SetString(PyExc_OverflowError,
12374 "string is too long to generate repr");
12375 return NULL;
12376 }
12377 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 }
12379
12380 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012381 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012383 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 if (dquote)
12385 /* Both squote and dquote present. Use squote,
12386 and escape them */
12387 osize += squote;
12388 else
12389 quote = '"';
12390 }
Victor Stinner55c08782013-04-14 18:45:39 +020012391 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392
12393 repr = PyUnicode_New(osize, max);
12394 if (repr == NULL)
12395 return NULL;
12396 okind = PyUnicode_KIND(repr);
12397 odata = PyUnicode_DATA(repr);
12398
12399 PyUnicode_WRITE(okind, odata, 0, quote);
12400 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012401 if (unchanged) {
12402 _PyUnicode_FastCopyCharacters(repr, 1,
12403 unicode, 0,
12404 isize);
12405 }
12406 else {
12407 for (i = 0, o = 1; i < isize; i++) {
12408 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409
Victor Stinner55c08782013-04-14 18:45:39 +020012410 /* Escape quotes and backslashes */
12411 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012412 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012414 continue;
12415 }
12416
12417 /* Map special whitespace to '\t', \n', '\r' */
12418 if (ch == '\t') {
12419 PyUnicode_WRITE(okind, odata, o++, '\\');
12420 PyUnicode_WRITE(okind, odata, o++, 't');
12421 }
12422 else if (ch == '\n') {
12423 PyUnicode_WRITE(okind, odata, o++, '\\');
12424 PyUnicode_WRITE(okind, odata, o++, 'n');
12425 }
12426 else if (ch == '\r') {
12427 PyUnicode_WRITE(okind, odata, o++, '\\');
12428 PyUnicode_WRITE(okind, odata, o++, 'r');
12429 }
12430
12431 /* Map non-printable US ASCII to '\xhh' */
12432 else if (ch < ' ' || ch == 0x7F) {
12433 PyUnicode_WRITE(okind, odata, o++, '\\');
12434 PyUnicode_WRITE(okind, odata, o++, 'x');
12435 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12436 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12437 }
12438
12439 /* Copy ASCII characters as-is */
12440 else if (ch < 0x7F) {
12441 PyUnicode_WRITE(okind, odata, o++, ch);
12442 }
12443
12444 /* Non-ASCII characters */
12445 else {
12446 /* Map Unicode whitespace and control characters
12447 (categories Z* and C* except ASCII space)
12448 */
12449 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12450 PyUnicode_WRITE(okind, odata, o++, '\\');
12451 /* Map 8-bit characters to '\xhh' */
12452 if (ch <= 0xff) {
12453 PyUnicode_WRITE(okind, odata, o++, 'x');
12454 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12455 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12456 }
12457 /* Map 16-bit characters to '\uxxxx' */
12458 else if (ch <= 0xffff) {
12459 PyUnicode_WRITE(okind, odata, o++, 'u');
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12461 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12462 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12463 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12464 }
12465 /* Map 21-bit characters to '\U00xxxxxx' */
12466 else {
12467 PyUnicode_WRITE(okind, odata, o++, 'U');
12468 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12469 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12470 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12471 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12472 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12473 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12474 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12475 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12476 }
12477 }
12478 /* Copy characters as-is */
12479 else {
12480 PyUnicode_WRITE(okind, odata, o++, ch);
12481 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012482 }
12483 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012484 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012485 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012486 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012487 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488}
12489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012490PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492\n\
12493Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012494such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012495arguments start and end are interpreted as in slice notation.\n\
12496\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012497Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
12499static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020012502 PyObject *substring = NULL;
12503 Py_ssize_t start = 0;
12504 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012505 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506
Jesus Ceaac451502011-04-20 17:09:23 +020012507 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12508 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012509 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510
Christian Heimesea71a522013-06-29 21:17:34 +020012511 if (PyUnicode_READY(self) == -1) {
12512 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012513 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012514 }
12515 if (PyUnicode_READY(substring) == -1) {
12516 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012517 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012518 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012519
Victor Stinner7931d9a2011-11-04 00:22:48 +010012520 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521
12522 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524 if (result == -2)
12525 return NULL;
12526
Christian Heimes217cfd12007-12-02 14:31:20 +000012527 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528}
12529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012530PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012531 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012533Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534
12535static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537{
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +020012538 PyObject *substring = NULL;
12539 Py_ssize_t start = 0;
12540 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012541 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542
Jesus Ceaac451502011-04-20 17:09:23 +020012543 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12544 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012545 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546
Christian Heimesea71a522013-06-29 21:17:34 +020012547 if (PyUnicode_READY(self) == -1) {
12548 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012550 }
12551 if (PyUnicode_READY(substring) == -1) {
12552 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012553 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555
Victor Stinner7931d9a2011-11-04 00:22:48 +010012556 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557
12558 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 if (result == -2)
12561 return NULL;
12562
Guido van Rossumd57fd912000-03-10 22:53:23 +000012563 if (result < 0) {
12564 PyErr_SetString(PyExc_ValueError, "substring not found");
12565 return NULL;
12566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567
Christian Heimes217cfd12007-12-02 14:31:20 +000012568 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012569}
12570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012571PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012574Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012575done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576
12577static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012578unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012580 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 Py_UCS4 fillchar = ' ';
12582
Victor Stinnere9a29352011-10-01 02:14:59 +020012583 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012585
Benjamin Petersonbac79492012-01-14 13:34:47 -050012586 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587 return NULL;
12588
Victor Stinnerc4b49542011-12-11 22:44:26 +010012589 if (PyUnicode_GET_LENGTH(self) >= width)
12590 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
Victor Stinnerc4b49542011-12-11 22:44:26 +010012592 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593}
12594
Alexander Belopolsky40018472011-02-26 01:02:56 +000012595PyObject *
12596PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597{
12598 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012599
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600 s = PyUnicode_FromObject(s);
12601 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012602 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012603 if (sep != NULL) {
12604 sep = PyUnicode_FromObject(sep);
12605 if (sep == NULL) {
12606 Py_DECREF(s);
12607 return NULL;
12608 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609 }
12610
Victor Stinner9310abb2011-10-05 00:59:23 +020012611 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612
12613 Py_DECREF(s);
12614 Py_XDECREF(sep);
12615 return result;
12616}
12617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012619 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620\n\
12621Return a list of the words in S, using sep as the\n\
12622delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012623splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012624whitespace string is a separator and empty strings are\n\
12625removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626
12627static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012628unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012630 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012632 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012634 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12635 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636 return NULL;
12637
12638 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012639 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012641 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012643 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012644}
12645
Thomas Wouters477c8d52006-05-27 19:21:47 +000012646PyObject *
12647PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12648{
12649 PyObject* str_obj;
12650 PyObject* sep_obj;
12651 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 int kind1, kind2, kind;
12653 void *buf1 = NULL, *buf2 = NULL;
12654 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012655
12656 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012657 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012658 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012659 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012660 if (!sep_obj) {
12661 Py_DECREF(str_obj);
12662 return NULL;
12663 }
12664 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12665 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012666 Py_DECREF(str_obj);
12667 return NULL;
12668 }
12669
Victor Stinner14f8f022011-10-05 20:58:25 +020012670 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012672 kind = Py_MAX(kind1, kind2);
12673 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012675 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 if (!buf1)
12677 goto onError;
12678 buf2 = PyUnicode_DATA(sep_obj);
12679 if (kind2 != kind)
12680 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12681 if (!buf2)
12682 goto onError;
12683 len1 = PyUnicode_GET_LENGTH(str_obj);
12684 len2 = PyUnicode_GET_LENGTH(sep_obj);
12685
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012686 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012688 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12689 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12690 else
12691 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 break;
12693 case PyUnicode_2BYTE_KIND:
12694 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12695 break;
12696 case PyUnicode_4BYTE_KIND:
12697 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12698 break;
12699 default:
12700 assert(0);
12701 out = 0;
12702 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012703
12704 Py_DECREF(sep_obj);
12705 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 if (kind1 != kind)
12707 PyMem_Free(buf1);
12708 if (kind2 != kind)
12709 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012710
12711 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 onError:
12713 Py_DECREF(sep_obj);
12714 Py_DECREF(str_obj);
12715 if (kind1 != kind && buf1)
12716 PyMem_Free(buf1);
12717 if (kind2 != kind && buf2)
12718 PyMem_Free(buf2);
12719 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012720}
12721
12722
12723PyObject *
12724PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12725{
12726 PyObject* str_obj;
12727 PyObject* sep_obj;
12728 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 int kind1, kind2, kind;
12730 void *buf1 = NULL, *buf2 = NULL;
12731 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012732
12733 str_obj = PyUnicode_FromObject(str_in);
12734 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012735 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012736 sep_obj = PyUnicode_FromObject(sep_in);
12737 if (!sep_obj) {
12738 Py_DECREF(str_obj);
12739 return NULL;
12740 }
12741
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012742 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012744 kind = Py_MAX(kind1, kind2);
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012745 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746 if (kind1 != kind)
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012747 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 if (!buf1)
12749 goto onError;
12750 buf2 = PyUnicode_DATA(sep_obj);
12751 if (kind2 != kind)
12752 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12753 if (!buf2)
12754 goto onError;
12755 len1 = PyUnicode_GET_LENGTH(str_obj);
12756 len2 = PyUnicode_GET_LENGTH(sep_obj);
12757
Serhiy Storchaka48070c12015-03-29 19:21:02 +030012758 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012760 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12761 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12762 else
12763 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 break;
12765 case PyUnicode_2BYTE_KIND:
12766 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12767 break;
12768 case PyUnicode_4BYTE_KIND:
12769 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12770 break;
12771 default:
12772 assert(0);
12773 out = 0;
12774 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012775
12776 Py_DECREF(sep_obj);
12777 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012778 if (kind1 != kind)
12779 PyMem_Free(buf1);
12780 if (kind2 != kind)
12781 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012782
12783 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 onError:
12785 Py_DECREF(sep_obj);
12786 Py_DECREF(str_obj);
12787 if (kind1 != kind && buf1)
12788 PyMem_Free(buf1);
12789 if (kind2 != kind && buf2)
12790 PyMem_Free(buf2);
12791 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012792}
12793
12794PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012795 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012796\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012797Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012798the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012799found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800
12801static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012802unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012803{
Victor Stinner9310abb2011-10-05 00:59:23 +020012804 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012805}
12806
12807PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012808 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012809\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012810Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012811the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012812separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012813
12814static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012815unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012816{
Victor Stinner9310abb2011-10-05 00:59:23 +020012817 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012818}
12819
Alexander Belopolsky40018472011-02-26 01:02:56 +000012820PyObject *
12821PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012822{
12823 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012824
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012825 s = PyUnicode_FromObject(s);
12826 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012827 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 if (sep != NULL) {
12829 sep = PyUnicode_FromObject(sep);
12830 if (sep == NULL) {
12831 Py_DECREF(s);
12832 return NULL;
12833 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012834 }
12835
Victor Stinner9310abb2011-10-05 00:59:23 +020012836 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012837
12838 Py_DECREF(s);
12839 Py_XDECREF(sep);
12840 return result;
12841}
12842
12843PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012844 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012845\n\
12846Return a list of the words in S, using sep as the\n\
12847delimiter string, starting at the end of the string and\n\
12848working to the front. If maxsplit is given, at most maxsplit\n\
12849splits are done. If sep is not specified, any whitespace string\n\
12850is a separator.");
12851
12852static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012853unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012854{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012855 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012856 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012857 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012858
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012859 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12860 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012861 return NULL;
12862
12863 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012864 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012865 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012866 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012867 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012868 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012869}
12870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012871PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012872 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012873\n\
12874Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012875Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012876is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
12878static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012879unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012881 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012882 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012884 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12885 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886 return NULL;
12887
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012888 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889}
12890
12891static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012892PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012893{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012894 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895}
12896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012897PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899\n\
12900Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012901and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902
12903static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012904unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012906 if (PyUnicode_READY(self) == -1)
12907 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012908 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012909}
12910
Larry Hastings61272b72014-01-07 12:41:53 -080012911/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012912
Larry Hastings31826802013-10-19 00:09:25 -070012913@staticmethod
12914str.maketrans as unicode_maketrans
12915
12916 x: object
12917
12918 y: unicode=NULL
12919
12920 z: unicode=NULL
12921
12922 /
12923
12924Return a translation table usable for str.translate().
12925
12926If there is only one argument, it must be a dictionary mapping Unicode
12927ordinals (integers) or characters to Unicode ordinals, strings or None.
12928Character keys will be then converted to ordinals.
12929If there are two arguments, they must be strings of equal length, and
12930in the resulting dictionary, each character in x will be mapped to the
12931character at the same position in y. If there is a third argument, it
12932must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012933[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012934
12935PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012936"maketrans(x, y=None, z=None, /)\n"
12937"--\n"
12938"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012939"Return a translation table usable for str.translate().\n"
12940"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012941"If there is only one argument, it must be a dictionary mapping Unicode\n"
12942"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12943"Character keys will be then converted to ordinals.\n"
12944"If there are two arguments, they must be strings of equal length, and\n"
12945"in the resulting dictionary, each character in x will be mapped to the\n"
12946"character at the same position in y. If there is a third argument, it\n"
12947"must be a string, whose characters will be mapped to None in the result.");
12948
12949#define UNICODE_MAKETRANS_METHODDEF \
12950 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12951
12952static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012953unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012954
12955static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012956unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012957{
Larry Hastings31826802013-10-19 00:09:25 -070012958 PyObject *return_value = NULL;
12959 PyObject *x;
12960 PyObject *y = NULL;
12961 PyObject *z = NULL;
12962
12963 if (!PyArg_ParseTuple(args,
12964 "O|UU:maketrans",
12965 &x, &y, &z))
12966 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012967 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012968
12969exit:
12970 return return_value;
12971}
12972
12973static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012974unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012975/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012976{
Georg Brandlceee0772007-11-27 23:48:05 +000012977 PyObject *new = NULL, *key, *value;
12978 Py_ssize_t i = 0;
12979 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012980
Georg Brandlceee0772007-11-27 23:48:05 +000012981 new = PyDict_New();
12982 if (!new)
12983 return NULL;
12984 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 int x_kind, y_kind, z_kind;
12986 void *x_data, *y_data, *z_data;
12987
Georg Brandlceee0772007-11-27 23:48:05 +000012988 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012989 if (!PyUnicode_Check(x)) {
12990 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12991 "be a string if there is a second argument");
12992 goto err;
12993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012995 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12996 "arguments must have equal length");
12997 goto err;
12998 }
12999 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 x_kind = PyUnicode_KIND(x);
13001 y_kind = PyUnicode_KIND(y);
13002 x_data = PyUnicode_DATA(x);
13003 y_data = PyUnicode_DATA(y);
13004 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13005 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013006 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013007 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013008 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013009 if (!value) {
13010 Py_DECREF(key);
13011 goto err;
13012 }
Georg Brandlceee0772007-11-27 23:48:05 +000013013 res = PyDict_SetItem(new, key, value);
13014 Py_DECREF(key);
13015 Py_DECREF(value);
13016 if (res < 0)
13017 goto err;
13018 }
13019 /* create entries for deleting chars in z */
13020 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021 z_kind = PyUnicode_KIND(z);
13022 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013023 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013024 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013025 if (!key)
13026 goto err;
13027 res = PyDict_SetItem(new, key, Py_None);
13028 Py_DECREF(key);
13029 if (res < 0)
13030 goto err;
13031 }
13032 }
13033 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 int kind;
13035 void *data;
13036
Georg Brandlceee0772007-11-27 23:48:05 +000013037 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013038 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013039 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13040 "to maketrans it must be a dict");
13041 goto err;
13042 }
13043 /* copy entries into the new dict, converting string keys to int keys */
13044 while (PyDict_Next(x, &i, &key, &value)) {
13045 if (PyUnicode_Check(key)) {
13046 /* convert string keys to integer keys */
13047 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013048 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013049 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13050 "table must be of length 1");
13051 goto err;
13052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013053 kind = PyUnicode_KIND(key);
13054 data = PyUnicode_DATA(key);
13055 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013056 if (!newkey)
13057 goto err;
13058 res = PyDict_SetItem(new, newkey, value);
13059 Py_DECREF(newkey);
13060 if (res < 0)
13061 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013062 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013063 /* just keep integer keys */
13064 if (PyDict_SetItem(new, key, value) < 0)
13065 goto err;
13066 } else {
13067 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13068 "be strings or integers");
13069 goto err;
13070 }
13071 }
13072 }
13073 return new;
13074 err:
13075 Py_DECREF(new);
13076 return NULL;
13077}
13078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013079PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013082Return a copy of the string S in which each character has been mapped\n\
13083through the given translation table. The table must implement\n\
13084lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13085mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13086this operation raises LookupError, the character is left untouched.\n\
13087Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
13089static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013090unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093}
13094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013095PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013098Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099
13100static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013101unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013102{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013103 if (PyUnicode_READY(self) == -1)
13104 return NULL;
13105 if (PyUnicode_IS_ASCII(self))
13106 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013107 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108}
13109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013113Pad a numeric string S with zeros on the left, to fill a field\n\
13114of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115
13116static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013117unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013119 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013120 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013121 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013122 int kind;
13123 void *data;
13124 Py_UCS4 chr;
13125
Martin v. Löwis18e16552006-02-15 17:27:45 +000013126 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127 return NULL;
13128
Benjamin Petersonbac79492012-01-14 13:34:47 -050013129 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131
Victor Stinnerc4b49542011-12-11 22:44:26 +010013132 if (PyUnicode_GET_LENGTH(self) >= width)
13133 return unicode_result_unchanged(self);
13134
13135 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136
13137 u = pad(self, fill, 0, '0');
13138
Walter Dörwald068325e2002-04-15 13:36:47 +000013139 if (u == NULL)
13140 return NULL;
13141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 kind = PyUnicode_KIND(u);
13143 data = PyUnicode_DATA(u);
13144 chr = PyUnicode_READ(kind, data, fill);
13145
13146 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013147 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013148 PyUnicode_WRITE(kind, data, 0, chr);
13149 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150 }
13151
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013152 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013153 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013155
13156#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013157static PyObject *
13158unicode__decimal2ascii(PyObject *self)
13159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013161}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162#endif
13163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013164PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013167Return True if S starts with the specified prefix, False otherwise.\n\
13168With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013169With optional end, stop comparing S at that position.\n\
13170prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171
13172static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013173unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013176 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013177 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013178 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013179 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181
Jesus Ceaac451502011-04-20 17:09:23 +020013182 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013183 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013184 if (PyTuple_Check(subobj)) {
13185 Py_ssize_t i;
13186 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013187 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013188 if (substring == NULL)
13189 return NULL;
13190 result = tailmatch(self, substring, start, end, -1);
13191 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013192 if (result == -1)
13193 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013194 if (result) {
13195 Py_RETURN_TRUE;
13196 }
13197 }
13198 /* nothing matched */
13199 Py_RETURN_FALSE;
13200 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013201 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013202 if (substring == NULL) {
13203 if (PyErr_ExceptionMatches(PyExc_TypeError))
13204 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13205 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013206 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013207 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013208 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013210 if (result == -1)
13211 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013212 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213}
13214
13215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013216PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013219Return True if S ends with the specified suffix, False otherwise.\n\
13220With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013221With optional end, stop comparing S at that position.\n\
13222suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223
13224static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013225unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013228 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013229 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013230 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013231 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013232 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233
Jesus Ceaac451502011-04-20 17:09:23 +020013234 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013235 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013236 if (PyTuple_Check(subobj)) {
13237 Py_ssize_t i;
13238 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013239 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013241 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013242 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013243 result = tailmatch(self, substring, start, end, +1);
13244 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013245 if (result == -1)
13246 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013247 if (result) {
13248 Py_RETURN_TRUE;
13249 }
13250 }
13251 Py_RETURN_FALSE;
13252 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013253 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013254 if (substring == NULL) {
13255 if (PyErr_ExceptionMatches(PyExc_TypeError))
13256 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13257 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013259 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013260 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013261 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013262 if (result == -1)
13263 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013264 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265}
13266
Victor Stinner202fdca2012-05-07 12:47:02 +020013267Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013268_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013269{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013270 if (!writer->readonly)
13271 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13272 else {
13273 /* Copy-on-write mode: set buffer size to 0 so
13274 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13275 * next write. */
13276 writer->size = 0;
13277 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013278 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13279 writer->data = PyUnicode_DATA(writer->buffer);
13280 writer->kind = PyUnicode_KIND(writer->buffer);
13281}
13282
Victor Stinnerd3f08822012-05-29 12:57:52 +020013283void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013284_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013285{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013286 memset(writer, 0, sizeof(*writer));
13287#ifdef Py_DEBUG
13288 writer->kind = 5; /* invalid kind */
13289#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013290 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013291}
13292
Victor Stinnerd3f08822012-05-29 12:57:52 +020013293int
13294_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13295 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013296{
Victor Stinner6989ba02013-11-18 21:08:39 +010013297#ifdef MS_WINDOWS
13298 /* On Windows, overallocate by 50% is the best factor */
13299# define OVERALLOCATE_FACTOR 2
13300#else
13301 /* On Linux, overallocate by 25% is the best factor */
13302# define OVERALLOCATE_FACTOR 4
13303#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013304 Py_ssize_t newlen;
13305 PyObject *newbuffer;
13306
Victor Stinnerd3f08822012-05-29 12:57:52 +020013307 assert(length > 0);
13308
Victor Stinner202fdca2012-05-07 12:47:02 +020013309 if (length > PY_SSIZE_T_MAX - writer->pos) {
13310 PyErr_NoMemory();
13311 return -1;
13312 }
13313 newlen = writer->pos + length;
13314
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013315 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013316
Victor Stinnerd3f08822012-05-29 12:57:52 +020013317 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013318 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013319 if (writer->overallocate
13320 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13321 /* overallocate to limit the number of realloc() */
13322 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013323 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013324 if (newlen < writer->min_length)
13325 newlen = writer->min_length;
13326
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 writer->buffer = PyUnicode_New(newlen, maxchar);
13328 if (writer->buffer == NULL)
13329 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013330 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013331 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013332 if (writer->overallocate
13333 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13334 /* overallocate to limit the number of realloc() */
13335 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013336 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013337 if (newlen < writer->min_length)
13338 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013339
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013340 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013341 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013342 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013343 newbuffer = PyUnicode_New(newlen, maxchar);
13344 if (newbuffer == NULL)
13345 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013346 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13347 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013348 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013349 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013350 }
13351 else {
13352 newbuffer = resize_compact(writer->buffer, newlen);
13353 if (newbuffer == NULL)
13354 return -1;
13355 }
13356 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013357 }
13358 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013359 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013360 newbuffer = PyUnicode_New(writer->size, maxchar);
13361 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013362 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013363 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13364 writer->buffer, 0, writer->pos);
13365 Py_DECREF(writer->buffer);
13366 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013367 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013368 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013369 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013370
13371#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013372}
13373
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013374Py_LOCAL_INLINE(int)
13375_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013376{
13377 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13378 return -1;
13379 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13380 writer->pos++;
13381 return 0;
13382}
13383
13384int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013385_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13386{
13387 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13388}
13389
13390int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013391_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13392{
13393 Py_UCS4 maxchar;
13394 Py_ssize_t len;
13395
13396 if (PyUnicode_READY(str) == -1)
13397 return -1;
13398 len = PyUnicode_GET_LENGTH(str);
13399 if (len == 0)
13400 return 0;
13401 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13402 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013403 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013404 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013405 Py_INCREF(str);
13406 writer->buffer = str;
13407 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013408 writer->pos += len;
13409 return 0;
13410 }
13411 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13412 return -1;
13413 }
13414 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13415 str, 0, len);
13416 writer->pos += len;
13417 return 0;
13418}
13419
Victor Stinnere215d962012-10-06 23:03:36 +020013420int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013421_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13422 Py_ssize_t start, Py_ssize_t end)
13423{
13424 Py_UCS4 maxchar;
13425 Py_ssize_t len;
13426
13427 if (PyUnicode_READY(str) == -1)
13428 return -1;
13429
13430 assert(0 <= start);
13431 assert(end <= PyUnicode_GET_LENGTH(str));
13432 assert(start <= end);
13433
13434 if (end == 0)
13435 return 0;
13436
13437 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13438 return _PyUnicodeWriter_WriteStr(writer, str);
13439
13440 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13441 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13442 else
13443 maxchar = writer->maxchar;
13444 len = end - start;
13445
13446 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13447 return -1;
13448
13449 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13450 str, start, len);
13451 writer->pos += len;
13452 return 0;
13453}
13454
13455int
Victor Stinner4a587072013-11-19 12:54:53 +010013456_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13457 const char *ascii, Py_ssize_t len)
13458{
13459 if (len == -1)
13460 len = strlen(ascii);
13461
13462 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13463
13464 if (writer->buffer == NULL && !writer->overallocate) {
13465 PyObject *str;
13466
13467 str = _PyUnicode_FromASCII(ascii, len);
13468 if (str == NULL)
13469 return -1;
13470
13471 writer->readonly = 1;
13472 writer->buffer = str;
13473 _PyUnicodeWriter_Update(writer);
13474 writer->pos += len;
13475 return 0;
13476 }
13477
13478 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13479 return -1;
13480
13481 switch (writer->kind)
13482 {
13483 case PyUnicode_1BYTE_KIND:
13484 {
13485 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13486 Py_UCS1 *data = writer->data;
13487
13488 Py_MEMCPY(data + writer->pos, str, len);
13489 break;
13490 }
13491 case PyUnicode_2BYTE_KIND:
13492 {
13493 _PyUnicode_CONVERT_BYTES(
13494 Py_UCS1, Py_UCS2,
13495 ascii, ascii + len,
13496 (Py_UCS2 *)writer->data + writer->pos);
13497 break;
13498 }
13499 case PyUnicode_4BYTE_KIND:
13500 {
13501 _PyUnicode_CONVERT_BYTES(
13502 Py_UCS1, Py_UCS4,
13503 ascii, ascii + len,
13504 (Py_UCS4 *)writer->data + writer->pos);
13505 break;
13506 }
13507 default:
13508 assert(0);
13509 }
13510
13511 writer->pos += len;
13512 return 0;
13513}
13514
13515int
13516_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13517 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013518{
13519 Py_UCS4 maxchar;
13520
13521 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13522 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13523 return -1;
13524 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13525 writer->pos += len;
13526 return 0;
13527}
13528
Victor Stinnerd3f08822012-05-29 12:57:52 +020013529PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013530_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013531{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013532 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013533 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013534 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013535 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013536 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013537 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013538 str = writer->buffer;
13539 writer->buffer = NULL;
13540 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13541 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013542 }
13543 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13544 PyObject *newbuffer;
13545 newbuffer = resize_compact(writer->buffer, writer->pos);
13546 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013547 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013548 return NULL;
13549 }
13550 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013551 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013552 str = writer->buffer;
13553 writer->buffer = NULL;
13554 assert(_PyUnicode_CheckConsistency(str, 1));
13555 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013556}
13557
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013559_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013560{
13561 Py_CLEAR(writer->buffer);
13562}
13563
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013564#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013565
13566PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013568\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013569Return a formatted version of S, using substitutions from args and kwargs.\n\
13570The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013571
Eric Smith27bbca62010-11-04 17:06:58 +000013572PyDoc_STRVAR(format_map__doc__,
13573 "S.format_map(mapping) -> str\n\
13574\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013575Return a formatted version of S, using substitutions from mapping.\n\
13576The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013577
Eric Smith4a7d76d2008-05-30 18:10:19 +000013578static PyObject *
13579unicode__format__(PyObject* self, PyObject* args)
13580{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013581 PyObject *format_spec;
13582 _PyUnicodeWriter writer;
13583 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013584
13585 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13586 return NULL;
13587
Victor Stinnerd3f08822012-05-29 12:57:52 +020013588 if (PyUnicode_READY(self) == -1)
13589 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013590 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013591 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13592 self, format_spec, 0,
13593 PyUnicode_GET_LENGTH(format_spec));
13594 if (ret == -1) {
13595 _PyUnicodeWriter_Dealloc(&writer);
13596 return NULL;
13597 }
13598 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013599}
13600
Eric Smith8c663262007-08-25 02:26:07 +000013601PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013602 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013603\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013604Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013605
13606static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013607unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013608{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013609 Py_ssize_t size;
13610
13611 /* If it's a compact object, account for base structure +
13612 character data. */
13613 if (PyUnicode_IS_COMPACT_ASCII(v))
13614 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13615 else if (PyUnicode_IS_COMPACT(v))
13616 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013617 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 else {
13619 /* If it is a two-block object, account for base object, and
13620 for character block if present. */
13621 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013622 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013623 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013624 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013625 }
13626 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013627 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013628 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013629 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013630 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013631 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013632
13633 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013634}
13635
13636PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013637 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013638
13639static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013640unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013641{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013642 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013643 if (!copy)
13644 return NULL;
13645 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013646}
13647
Guido van Rossumd57fd912000-03-10 22:53:23 +000013648static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013649 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013650 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013651 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13652 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013653 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13654 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013655 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013656 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13657 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13658 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013659 {"expandtabs", (PyCFunction) unicode_expandtabs,
13660 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013661 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013662 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013663 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13664 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13665 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013666 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013667 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13668 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13669 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013670 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013671 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013672 {"splitlines", (PyCFunction) unicode_splitlines,
13673 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013674 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013675 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13676 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13677 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13678 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13679 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13680 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13681 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13682 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13683 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13684 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13685 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13686 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13687 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13688 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013689 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013690 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013691 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013692 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013693 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013694 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013695 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013696 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013697#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013698 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013699 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013700#endif
13701
Benjamin Peterson14339b62009-01-31 16:36:08 +000013702 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013703 {NULL, NULL}
13704};
13705
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013706static PyObject *
13707unicode_mod(PyObject *v, PyObject *w)
13708{
Brian Curtindfc80e32011-08-10 20:28:54 -050013709 if (!PyUnicode_Check(v))
13710 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013711 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013712}
13713
13714static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013715 0, /*nb_add*/
13716 0, /*nb_subtract*/
13717 0, /*nb_multiply*/
13718 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013719};
13720
Guido van Rossumd57fd912000-03-10 22:53:23 +000013721static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013722 (lenfunc) unicode_length, /* sq_length */
13723 PyUnicode_Concat, /* sq_concat */
13724 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13725 (ssizeargfunc) unicode_getitem, /* sq_item */
13726 0, /* sq_slice */
13727 0, /* sq_ass_item */
13728 0, /* sq_ass_slice */
13729 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013730};
13731
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013732static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013733unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013734{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013735 if (PyUnicode_READY(self) == -1)
13736 return NULL;
13737
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013738 if (PyIndex_Check(item)) {
13739 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013740 if (i == -1 && PyErr_Occurred())
13741 return NULL;
13742 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013743 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013744 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013745 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013746 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013747 PyObject *result;
13748 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013749 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013750 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013752 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013753 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013754 return NULL;
13755 }
13756
13757 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013758 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013759 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013760 slicelength == PyUnicode_GET_LENGTH(self)) {
13761 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013762 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013763 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013764 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013765 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013766 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013767 src_kind = PyUnicode_KIND(self);
13768 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013769 if (!PyUnicode_IS_ASCII(self)) {
13770 kind_limit = kind_maxchar_limit(src_kind);
13771 max_char = 0;
13772 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13773 ch = PyUnicode_READ(src_kind, src_data, cur);
13774 if (ch > max_char) {
13775 max_char = ch;
13776 if (max_char >= kind_limit)
13777 break;
13778 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013779 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013780 }
Victor Stinner55c99112011-10-13 01:17:06 +020013781 else
13782 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013783 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013784 if (result == NULL)
13785 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013786 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013787 dest_data = PyUnicode_DATA(result);
13788
13789 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013790 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13791 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013792 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013793 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013794 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013795 } else {
13796 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13797 return NULL;
13798 }
13799}
13800
13801static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013802 (lenfunc)unicode_length, /* mp_length */
13803 (binaryfunc)unicode_subscript, /* mp_subscript */
13804 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013805};
13806
Guido van Rossumd57fd912000-03-10 22:53:23 +000013807
Guido van Rossumd57fd912000-03-10 22:53:23 +000013808/* Helpers for PyUnicode_Format() */
13809
Victor Stinnera47082312012-10-04 02:19:54 +020013810struct unicode_formatter_t {
13811 PyObject *args;
13812 int args_owned;
13813 Py_ssize_t arglen, argidx;
13814 PyObject *dict;
13815
13816 enum PyUnicode_Kind fmtkind;
13817 Py_ssize_t fmtcnt, fmtpos;
13818 void *fmtdata;
13819 PyObject *fmtstr;
13820
13821 _PyUnicodeWriter writer;
13822};
13823
13824struct unicode_format_arg_t {
13825 Py_UCS4 ch;
13826 int flags;
13827 Py_ssize_t width;
13828 int prec;
13829 int sign;
13830};
13831
Guido van Rossumd57fd912000-03-10 22:53:23 +000013832static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013833unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013834{
Victor Stinnera47082312012-10-04 02:19:54 +020013835 Py_ssize_t argidx = ctx->argidx;
13836
13837 if (argidx < ctx->arglen) {
13838 ctx->argidx++;
13839 if (ctx->arglen < 0)
13840 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013841 else
Victor Stinnera47082312012-10-04 02:19:54 +020013842 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013843 }
13844 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013846 return NULL;
13847}
13848
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013849/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013850
Victor Stinnera47082312012-10-04 02:19:54 +020013851/* Format a float into the writer if the writer is not NULL, or into *p_output
13852 otherwise.
13853
13854 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013855static int
Victor Stinnera47082312012-10-04 02:19:54 +020013856formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13857 PyObject **p_output,
13858 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013859{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013860 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013862 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013863 int prec;
13864 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013865
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866 x = PyFloat_AsDouble(v);
13867 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013868 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013869
Victor Stinnera47082312012-10-04 02:19:54 +020013870 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013871 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013872 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013873
Victor Stinnera47082312012-10-04 02:19:54 +020013874 if (arg->flags & F_ALT)
13875 dtoa_flags = Py_DTSF_ALT;
13876 else
13877 dtoa_flags = 0;
13878 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013879 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013880 return -1;
13881 len = strlen(p);
13882 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013883 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013884 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013885 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013886 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013887 }
13888 else
13889 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013890 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013891 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892}
13893
Victor Stinnerd0880d52012-04-27 23:40:13 +020013894/* formatlong() emulates the format codes d, u, o, x and X, and
13895 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13896 * Python's regular ints.
13897 * Return value: a new PyUnicodeObject*, or NULL if error.
13898 * The output string is of the form
13899 * "-"? ("0x" | "0X")? digit+
13900 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13901 * set in flags. The case of hex digits will be correct,
13902 * There will be at least prec digits, zero-filled on the left if
13903 * necessary to get that many.
13904 * val object to be converted
13905 * flags bitmask of format flags; only F_ALT is looked at
13906 * prec minimum number of digits; 0-fill on left if needed
13907 * type a character in [duoxX]; u acts the same as d
13908 *
13909 * CAUTION: o, x and X conversions on regular ints can never
13910 * produce a '-' sign, but can for Python's unbounded ints.
13911 */
Tim Peters38fd5b62000-09-21 05:43:11 +000013912static PyObject*
Victor Stinnera47082312012-10-04 02:19:54 +020013913formatlong(PyObject *val, struct unicode_format_arg_t *arg)
Tim Peters38fd5b62000-09-21 05:43:11 +000013914{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013915 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013916 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013917 Py_ssize_t i;
13918 int sign; /* 1 if '-', else 0 */
13919 int len; /* number of characters */
13920 Py_ssize_t llen;
13921 int numdigits; /* len == numnondigits + numdigits */
13922 int numnondigits = 0;
Victor Stinnera47082312012-10-04 02:19:54 +020013923 int prec = arg->prec;
13924 int type = arg->ch;
Tim Peters38fd5b62000-09-21 05:43:11 +000013925
Victor Stinnerd0880d52012-04-27 23:40:13 +020013926 /* Avoid exceeding SSIZE_T_MAX */
13927 if (prec > INT_MAX-3) {
13928 PyErr_SetString(PyExc_OverflowError,
13929 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013930 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013931 }
13932
13933 assert(PyLong_Check(val));
13934
13935 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013936 default:
13937 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013938 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013939 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013940 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013941 /* int and int subclasses should print numerically when a numeric */
13942 /* format code is used (see issue18780) */
13943 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 break;
13945 case 'o':
13946 numnondigits = 2;
13947 result = PyNumber_ToBase(val, 8);
13948 break;
13949 case 'x':
13950 case 'X':
13951 numnondigits = 2;
13952 result = PyNumber_ToBase(val, 16);
13953 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013954 }
13955 if (!result)
13956 return NULL;
13957
13958 assert(unicode_modifiable(result));
13959 assert(PyUnicode_IS_READY(result));
13960 assert(PyUnicode_IS_ASCII(result));
13961
13962 /* To modify the string in-place, there can only be one reference. */
13963 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013964 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013965 PyErr_BadInternalCall();
13966 return NULL;
13967 }
13968 buf = PyUnicode_DATA(result);
13969 llen = PyUnicode_GET_LENGTH(result);
13970 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013971 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013972 PyErr_SetString(PyExc_ValueError,
13973 "string too large in _PyBytes_FormatLong");
13974 return NULL;
13975 }
13976 len = (int)llen;
13977 sign = buf[0] == '-';
13978 numnondigits += sign;
13979 numdigits = len - numnondigits;
13980 assert(numdigits > 0);
13981
13982 /* Get rid of base marker unless F_ALT */
Victor Stinnera47082312012-10-04 02:19:54 +020013983 if (((arg->flags & F_ALT) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013984 (type == 'o' || type == 'x' || type == 'X'))) {
13985 assert(buf[sign] == '0');
13986 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13987 buf[sign+1] == 'o');
13988 numnondigits -= 2;
13989 buf += 2;
13990 len -= 2;
13991 if (sign)
13992 buf[0] = '-';
13993 assert(len == numnondigits + numdigits);
13994 assert(numdigits > 0);
13995 }
13996
13997 /* Fill with leading zeroes to meet minimum width. */
13998 if (prec > numdigits) {
13999 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14000 numnondigits + prec);
14001 char *b1;
14002 if (!r1) {
14003 Py_DECREF(result);
14004 return NULL;
14005 }
14006 b1 = PyBytes_AS_STRING(r1);
14007 for (i = 0; i < numnondigits; ++i)
14008 *b1++ = *buf++;
14009 for (i = 0; i < prec - numdigits; i++)
14010 *b1++ = '0';
14011 for (i = 0; i < numdigits; i++)
14012 *b1++ = *buf++;
14013 *b1 = '\0';
14014 Py_DECREF(result);
14015 result = r1;
14016 buf = PyBytes_AS_STRING(result);
14017 len = numnondigits + prec;
14018 }
14019
14020 /* Fix up case for hex conversions. */
14021 if (type == 'X') {
14022 /* Need to convert all lower case letters to upper case.
14023 and need to convert 0x to 0X (and -0x to -0X). */
14024 for (i = 0; i < len; i++)
14025 if (buf[i] >= 'a' && buf[i] <= 'x')
14026 buf[i] -= 'a'-'A';
14027 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014028 if (!PyUnicode_Check(result)
14029 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014030 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014031 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014032 Py_DECREF(result);
14033 result = unicode;
14034 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014035 else if (len != PyUnicode_GET_LENGTH(result)) {
14036 if (PyUnicode_Resize(&result, len) < 0)
14037 Py_CLEAR(result);
14038 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014040}
14041
Ethan Furmandf3ed242014-01-05 06:50:30 -080014042/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014043 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014044 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014045 * -1 and raise an exception on error */
14046static int
Victor Stinnera47082312012-10-04 02:19:54 +020014047mainformatlong(PyObject *v,
14048 struct unicode_format_arg_t *arg,
14049 PyObject **p_output,
14050 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014051{
14052 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014053 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014054
14055 if (!PyNumber_Check(v))
14056 goto wrongtype;
14057
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014058 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014059 /* if not, issue deprecation warning for now */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014060 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014061 if (type == 'o' || type == 'x' || type == 'X') {
14062 iobj = PyNumber_Index(v);
14063 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014064 PyErr_Clear();
14065 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14066 "automatic int conversions have been deprecated",
14067 1)) {
14068 return -1;
14069 }
14070 iobj = PyNumber_Long(v);
14071 if (iobj == NULL ) {
14072 if (PyErr_ExceptionMatches(PyExc_TypeError))
14073 goto wrongtype;
14074 return -1;
14075 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014076 }
14077 }
14078 else {
14079 iobj = PyNumber_Long(v);
14080 if (iobj == NULL ) {
14081 if (PyErr_ExceptionMatches(PyExc_TypeError))
14082 goto wrongtype;
14083 return -1;
14084 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014085 }
14086 assert(PyLong_Check(iobj));
14087 }
14088 else {
14089 iobj = v;
14090 Py_INCREF(iobj);
14091 }
14092
14093 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014094 && arg->width == -1 && arg->prec == -1
14095 && !(arg->flags & (F_SIGN | F_BLANK))
14096 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014097 {
14098 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014099 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014100 int base;
14101
Victor Stinnera47082312012-10-04 02:19:54 +020014102 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103 {
14104 default:
14105 assert(0 && "'type' not in [diuoxX]");
14106 case 'd':
14107 case 'i':
14108 case 'u':
14109 base = 10;
14110 break;
14111 case 'o':
14112 base = 8;
14113 break;
14114 case 'x':
14115 case 'X':
14116 base = 16;
14117 break;
14118 }
14119
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014120 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14121 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014122 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014123 }
14124 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014125 return 1;
14126 }
14127
Victor Stinnera47082312012-10-04 02:19:54 +020014128 res = formatlong(iobj, arg);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014129 Py_DECREF(iobj);
14130 if (res == NULL)
14131 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014132 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014133 return 0;
14134
14135wrongtype:
14136 PyErr_Format(PyExc_TypeError,
14137 "%%%c format: a number is required, "
Victor Stinnera47082312012-10-04 02:19:54 +020014138 "not %.200s",
14139 type, Py_TYPE(v)->tp_name);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014140 return -1;
14141}
14142
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014143static Py_UCS4
14144formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014145{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014146 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014147 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014148 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014149 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014150 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014151 goto onError;
14152 }
14153 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014154 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014155 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014156 /* make sure number is a type of integer */
Ethan Furmana70805e2014-01-12 08:42:35 -080014157 /* if not, issue deprecation warning for now */
Ethan Furmandf3ed242014-01-05 06:50:30 -080014158 if (!PyLong_Check(v)) {
14159 iobj = PyNumber_Index(v);
14160 if (iobj == NULL) {
Ethan Furmanf9bba9c2014-01-11 23:20:58 -080014161 PyErr_Clear();
14162 if (PyErr_WarnEx(PyExc_DeprecationWarning,
14163 "automatic int conversions have been deprecated",
14164 1)) {
14165 return -1;
14166 }
14167 iobj = PyNumber_Long(v);
14168 if (iobj == NULL ) {
14169 if (PyErr_ExceptionMatches(PyExc_TypeError))
14170 goto onError;
14171 return -1;
14172 }
Ethan Furmandf3ed242014-01-05 06:50:30 -080014173 }
14174 v = iobj;
14175 Py_DECREF(iobj);
14176 }
14177 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014178 x = PyLong_AsLong(v);
14179 if (x == -1 && PyErr_Occurred())
14180 goto onError;
14181
Victor Stinner8faf8212011-12-08 22:14:11 +010014182 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014183 PyErr_SetString(PyExc_OverflowError,
14184 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014185 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014186 }
14187
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014188 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014189 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014190
Benjamin Peterson29060642009-01-31 22:14:21 +000014191 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014192 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014193 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014194 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014195}
14196
Victor Stinnera47082312012-10-04 02:19:54 +020014197/* Parse options of an argument: flags, width, precision.
14198 Handle also "%(name)" syntax.
14199
14200 Return 0 if the argument has been formatted into arg->str.
14201 Return 1 if the argument has been written into ctx->writer,
14202 Raise an exception and return -1 on error. */
14203static int
14204unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14205 struct unicode_format_arg_t *arg)
14206{
14207#define FORMAT_READ(ctx) \
14208 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14209
14210 PyObject *v;
14211
Victor Stinnera47082312012-10-04 02:19:54 +020014212 if (arg->ch == '(') {
14213 /* Get argument value from a dictionary. Example: "%(name)s". */
14214 Py_ssize_t keystart;
14215 Py_ssize_t keylen;
14216 PyObject *key;
14217 int pcount = 1;
14218
14219 if (ctx->dict == NULL) {
14220 PyErr_SetString(PyExc_TypeError,
14221 "format requires a mapping");
14222 return -1;
14223 }
14224 ++ctx->fmtpos;
14225 --ctx->fmtcnt;
14226 keystart = ctx->fmtpos;
14227 /* Skip over balanced parentheses */
14228 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14229 arg->ch = FORMAT_READ(ctx);
14230 if (arg->ch == ')')
14231 --pcount;
14232 else if (arg->ch == '(')
14233 ++pcount;
14234 ctx->fmtpos++;
14235 }
14236 keylen = ctx->fmtpos - keystart - 1;
14237 if (ctx->fmtcnt < 0 || pcount > 0) {
14238 PyErr_SetString(PyExc_ValueError,
14239 "incomplete format key");
14240 return -1;
14241 }
14242 key = PyUnicode_Substring(ctx->fmtstr,
14243 keystart, keystart + keylen);
14244 if (key == NULL)
14245 return -1;
14246 if (ctx->args_owned) {
14247 Py_DECREF(ctx->args);
14248 ctx->args_owned = 0;
14249 }
14250 ctx->args = PyObject_GetItem(ctx->dict, key);
14251 Py_DECREF(key);
14252 if (ctx->args == NULL)
14253 return -1;
14254 ctx->args_owned = 1;
14255 ctx->arglen = -1;
14256 ctx->argidx = -2;
14257 }
14258
14259 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014260 while (--ctx->fmtcnt >= 0) {
14261 arg->ch = FORMAT_READ(ctx);
14262 ctx->fmtpos++;
14263 switch (arg->ch) {
14264 case '-': arg->flags |= F_LJUST; continue;
14265 case '+': arg->flags |= F_SIGN; continue;
14266 case ' ': arg->flags |= F_BLANK; continue;
14267 case '#': arg->flags |= F_ALT; continue;
14268 case '0': arg->flags |= F_ZERO; continue;
14269 }
14270 break;
14271 }
14272
14273 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014274 if (arg->ch == '*') {
14275 v = unicode_format_getnextarg(ctx);
14276 if (v == NULL)
14277 return -1;
14278 if (!PyLong_Check(v)) {
14279 PyErr_SetString(PyExc_TypeError,
14280 "* wants int");
14281 return -1;
14282 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014283 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014284 if (arg->width == -1 && PyErr_Occurred())
14285 return -1;
14286 if (arg->width < 0) {
14287 arg->flags |= F_LJUST;
14288 arg->width = -arg->width;
14289 }
14290 if (--ctx->fmtcnt >= 0) {
14291 arg->ch = FORMAT_READ(ctx);
14292 ctx->fmtpos++;
14293 }
14294 }
14295 else if (arg->ch >= '0' && arg->ch <= '9') {
14296 arg->width = arg->ch - '0';
14297 while (--ctx->fmtcnt >= 0) {
14298 arg->ch = FORMAT_READ(ctx);
14299 ctx->fmtpos++;
14300 if (arg->ch < '0' || arg->ch > '9')
14301 break;
14302 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14303 mixing signed and unsigned comparison. Since arg->ch is between
14304 '0' and '9', casting to int is safe. */
14305 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14306 PyErr_SetString(PyExc_ValueError,
14307 "width too big");
14308 return -1;
14309 }
14310 arg->width = arg->width*10 + (arg->ch - '0');
14311 }
14312 }
14313
14314 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014315 if (arg->ch == '.') {
14316 arg->prec = 0;
14317 if (--ctx->fmtcnt >= 0) {
14318 arg->ch = FORMAT_READ(ctx);
14319 ctx->fmtpos++;
14320 }
14321 if (arg->ch == '*') {
14322 v = unicode_format_getnextarg(ctx);
14323 if (v == NULL)
14324 return -1;
14325 if (!PyLong_Check(v)) {
14326 PyErr_SetString(PyExc_TypeError,
14327 "* wants int");
14328 return -1;
14329 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014330 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014331 if (arg->prec == -1 && PyErr_Occurred())
14332 return -1;
14333 if (arg->prec < 0)
14334 arg->prec = 0;
14335 if (--ctx->fmtcnt >= 0) {
14336 arg->ch = FORMAT_READ(ctx);
14337 ctx->fmtpos++;
14338 }
14339 }
14340 else if (arg->ch >= '0' && arg->ch <= '9') {
14341 arg->prec = arg->ch - '0';
14342 while (--ctx->fmtcnt >= 0) {
14343 arg->ch = FORMAT_READ(ctx);
14344 ctx->fmtpos++;
14345 if (arg->ch < '0' || arg->ch > '9')
14346 break;
14347 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14348 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014349 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014350 return -1;
14351 }
14352 arg->prec = arg->prec*10 + (arg->ch - '0');
14353 }
14354 }
14355 }
14356
14357 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14358 if (ctx->fmtcnt >= 0) {
14359 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14360 if (--ctx->fmtcnt >= 0) {
14361 arg->ch = FORMAT_READ(ctx);
14362 ctx->fmtpos++;
14363 }
14364 }
14365 }
14366 if (ctx->fmtcnt < 0) {
14367 PyErr_SetString(PyExc_ValueError,
14368 "incomplete format");
14369 return -1;
14370 }
14371 return 0;
14372
14373#undef FORMAT_READ
14374}
14375
14376/* Format one argument. Supported conversion specifiers:
14377
14378 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014379 - "i", "d", "u": int or float
14380 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014381 - "e", "E", "f", "F", "g", "G": float
14382 - "c": int or str (1 character)
14383
Victor Stinner8dbd4212012-12-04 09:30:24 +010014384 When possible, the output is written directly into the Unicode writer
14385 (ctx->writer). A string is created when padding is required.
14386
Victor Stinnera47082312012-10-04 02:19:54 +020014387 Return 0 if the argument has been formatted into *p_str,
14388 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014389 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014390static int
14391unicode_format_arg_format(struct unicode_formatter_t *ctx,
14392 struct unicode_format_arg_t *arg,
14393 PyObject **p_str)
14394{
14395 PyObject *v;
14396 _PyUnicodeWriter *writer = &ctx->writer;
14397
14398 if (ctx->fmtcnt == 0)
14399 ctx->writer.overallocate = 0;
14400
14401 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014402 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014403 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014404 return 1;
14405 }
14406
14407 v = unicode_format_getnextarg(ctx);
14408 if (v == NULL)
14409 return -1;
14410
Victor Stinnera47082312012-10-04 02:19:54 +020014411
14412 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014413 case 's':
14414 case 'r':
14415 case 'a':
14416 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14417 /* Fast path */
14418 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14419 return -1;
14420 return 1;
14421 }
14422
14423 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14424 *p_str = v;
14425 Py_INCREF(*p_str);
14426 }
14427 else {
14428 if (arg->ch == 's')
14429 *p_str = PyObject_Str(v);
14430 else if (arg->ch == 'r')
14431 *p_str = PyObject_Repr(v);
14432 else
14433 *p_str = PyObject_ASCII(v);
14434 }
14435 break;
14436
14437 case 'i':
14438 case 'd':
14439 case 'u':
14440 case 'o':
14441 case 'x':
14442 case 'X':
14443 {
14444 int ret = mainformatlong(v, arg, p_str, writer);
14445 if (ret != 0)
14446 return ret;
14447 arg->sign = 1;
14448 break;
14449 }
14450
14451 case 'e':
14452 case 'E':
14453 case 'f':
14454 case 'F':
14455 case 'g':
14456 case 'G':
14457 if (arg->width == -1 && arg->prec == -1
14458 && !(arg->flags & (F_SIGN | F_BLANK)))
14459 {
14460 /* Fast path */
14461 if (formatfloat(v, arg, NULL, writer) == -1)
14462 return -1;
14463 return 1;
14464 }
14465
14466 arg->sign = 1;
14467 if (formatfloat(v, arg, p_str, NULL) == -1)
14468 return -1;
14469 break;
14470
14471 case 'c':
14472 {
14473 Py_UCS4 ch = formatchar(v);
14474 if (ch == (Py_UCS4) -1)
14475 return -1;
14476 if (arg->width == -1 && arg->prec == -1) {
14477 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014478 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014479 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014480 return 1;
14481 }
14482 *p_str = PyUnicode_FromOrdinal(ch);
14483 break;
14484 }
14485
14486 default:
14487 PyErr_Format(PyExc_ValueError,
14488 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014489 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014490 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14491 (int)arg->ch,
14492 ctx->fmtpos - 1);
14493 return -1;
14494 }
14495 if (*p_str == NULL)
14496 return -1;
14497 assert (PyUnicode_Check(*p_str));
14498 return 0;
14499}
14500
14501static int
14502unicode_format_arg_output(struct unicode_formatter_t *ctx,
14503 struct unicode_format_arg_t *arg,
14504 PyObject *str)
14505{
14506 Py_ssize_t len;
14507 enum PyUnicode_Kind kind;
14508 void *pbuf;
14509 Py_ssize_t pindex;
14510 Py_UCS4 signchar;
14511 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014512 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014513 Py_ssize_t sublen;
14514 _PyUnicodeWriter *writer = &ctx->writer;
14515 Py_UCS4 fill;
14516
14517 fill = ' ';
14518 if (arg->sign && arg->flags & F_ZERO)
14519 fill = '0';
14520
14521 if (PyUnicode_READY(str) == -1)
14522 return -1;
14523
14524 len = PyUnicode_GET_LENGTH(str);
14525 if ((arg->width == -1 || arg->width <= len)
14526 && (arg->prec == -1 || arg->prec >= len)
14527 && !(arg->flags & (F_SIGN | F_BLANK)))
14528 {
14529 /* Fast path */
14530 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14531 return -1;
14532 return 0;
14533 }
14534
14535 /* Truncate the string for "s", "r" and "a" formats
14536 if the precision is set */
14537 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14538 if (arg->prec >= 0 && len > arg->prec)
14539 len = arg->prec;
14540 }
14541
14542 /* Adjust sign and width */
14543 kind = PyUnicode_KIND(str);
14544 pbuf = PyUnicode_DATA(str);
14545 pindex = 0;
14546 signchar = '\0';
14547 if (arg->sign) {
14548 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14549 if (ch == '-' || ch == '+') {
14550 signchar = ch;
14551 len--;
14552 pindex++;
14553 }
14554 else if (arg->flags & F_SIGN)
14555 signchar = '+';
14556 else if (arg->flags & F_BLANK)
14557 signchar = ' ';
14558 else
14559 arg->sign = 0;
14560 }
14561 if (arg->width < len)
14562 arg->width = len;
14563
14564 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014565 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014566 if (!(arg->flags & F_LJUST)) {
14567 if (arg->sign) {
14568 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014569 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014570 }
14571 else {
14572 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014573 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014574 }
14575 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014576 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14577 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014578 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014579 }
14580
Victor Stinnera47082312012-10-04 02:19:54 +020014581 buflen = arg->width;
14582 if (arg->sign && len == arg->width)
14583 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014584 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014585 return -1;
14586
14587 /* Write the sign if needed */
14588 if (arg->sign) {
14589 if (fill != ' ') {
14590 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14591 writer->pos += 1;
14592 }
14593 if (arg->width > len)
14594 arg->width--;
14595 }
14596
14597 /* Write the numeric prefix for "x", "X" and "o" formats
14598 if the alternate form is used.
14599 For example, write "0x" for the "%#x" format. */
14600 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14601 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14602 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14603 if (fill != ' ') {
14604 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14605 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14606 writer->pos += 2;
14607 pindex += 2;
14608 }
14609 arg->width -= 2;
14610 if (arg->width < 0)
14611 arg->width = 0;
14612 len -= 2;
14613 }
14614
14615 /* Pad left with the fill character if needed */
14616 if (arg->width > len && !(arg->flags & F_LJUST)) {
14617 sublen = arg->width - len;
14618 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14619 writer->pos += sublen;
14620 arg->width = len;
14621 }
14622
14623 /* If padding with spaces: write sign if needed and/or numeric prefix if
14624 the alternate form is used */
14625 if (fill == ' ') {
14626 if (arg->sign) {
14627 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14628 writer->pos += 1;
14629 }
14630 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14631 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14632 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14633 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14634 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14635 writer->pos += 2;
14636 pindex += 2;
14637 }
14638 }
14639
14640 /* Write characters */
14641 if (len) {
14642 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14643 str, pindex, len);
14644 writer->pos += len;
14645 }
14646
14647 /* Pad right with the fill character if needed */
14648 if (arg->width > len) {
14649 sublen = arg->width - len;
14650 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14651 writer->pos += sublen;
14652 }
14653 return 0;
14654}
14655
14656/* Helper of PyUnicode_Format(): format one arg.
14657 Return 0 on success, raise an exception and return -1 on error. */
14658static int
14659unicode_format_arg(struct unicode_formatter_t *ctx)
14660{
14661 struct unicode_format_arg_t arg;
14662 PyObject *str;
14663 int ret;
14664
Victor Stinner8dbd4212012-12-04 09:30:24 +010014665 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14666 arg.flags = 0;
14667 arg.width = -1;
14668 arg.prec = -1;
14669 arg.sign = 0;
14670 str = NULL;
14671
Victor Stinnera47082312012-10-04 02:19:54 +020014672 ret = unicode_format_arg_parse(ctx, &arg);
14673 if (ret == -1)
14674 return -1;
14675
14676 ret = unicode_format_arg_format(ctx, &arg, &str);
14677 if (ret == -1)
14678 return -1;
14679
14680 if (ret != 1) {
14681 ret = unicode_format_arg_output(ctx, &arg, str);
14682 Py_DECREF(str);
14683 if (ret == -1)
14684 return -1;
14685 }
14686
14687 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14688 PyErr_SetString(PyExc_TypeError,
14689 "not all arguments converted during string formatting");
14690 return -1;
14691 }
14692 return 0;
14693}
14694
Alexander Belopolsky40018472011-02-26 01:02:56 +000014695PyObject *
14696PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014697{
Victor Stinnera47082312012-10-04 02:19:54 +020014698 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014699
Guido van Rossumd57fd912000-03-10 22:53:23 +000014700 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014701 PyErr_BadInternalCall();
14702 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014703 }
Victor Stinnera47082312012-10-04 02:19:54 +020014704
14705 ctx.fmtstr = PyUnicode_FromObject(format);
14706 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014707 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014708 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14709 Py_DECREF(ctx.fmtstr);
14710 return NULL;
14711 }
14712 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14713 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14714 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14715 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014716
Victor Stinner8f674cc2013-04-17 23:02:17 +020014717 _PyUnicodeWriter_Init(&ctx.writer);
14718 ctx.writer.min_length = ctx.fmtcnt + 100;
14719 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014720
Guido van Rossumd57fd912000-03-10 22:53:23 +000014721 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014722 ctx.arglen = PyTuple_Size(args);
14723 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014724 }
14725 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014726 ctx.arglen = -1;
14727 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014728 }
Victor Stinnera47082312012-10-04 02:19:54 +020014729 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014730 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014731 ctx.dict = args;
14732 else
14733 ctx.dict = NULL;
14734 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014735
Victor Stinnera47082312012-10-04 02:19:54 +020014736 while (--ctx.fmtcnt >= 0) {
14737 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014738 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014739
14740 nonfmtpos = ctx.fmtpos++;
14741 while (ctx.fmtcnt >= 0 &&
14742 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14743 ctx.fmtpos++;
14744 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014745 }
Victor Stinnera47082312012-10-04 02:19:54 +020014746 if (ctx.fmtcnt < 0) {
14747 ctx.fmtpos--;
14748 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014749 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014750
Victor Stinnercfc4c132013-04-03 01:48:39 +020014751 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14752 nonfmtpos, ctx.fmtpos) < 0)
14753 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014754 }
14755 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014756 ctx.fmtpos++;
14757 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014758 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014759 }
14760 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014761
Victor Stinnera47082312012-10-04 02:19:54 +020014762 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014763 PyErr_SetString(PyExc_TypeError,
14764 "not all arguments converted during string formatting");
14765 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014766 }
14767
Victor Stinnera47082312012-10-04 02:19:54 +020014768 if (ctx.args_owned) {
14769 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014770 }
Victor Stinnera47082312012-10-04 02:19:54 +020014771 Py_DECREF(ctx.fmtstr);
14772 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014773
Benjamin Peterson29060642009-01-31 22:14:21 +000014774 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014775 Py_DECREF(ctx.fmtstr);
14776 _PyUnicodeWriter_Dealloc(&ctx.writer);
14777 if (ctx.args_owned) {
14778 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014779 }
14780 return NULL;
14781}
14782
Jeremy Hylton938ace62002-07-17 16:30:39 +000014783static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014784unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14785
Tim Peters6d6c1a32001-08-02 04:15:00 +000014786static PyObject *
14787unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14788{
Benjamin Peterson29060642009-01-31 22:14:21 +000014789 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014790 static char *kwlist[] = {"object", "encoding", "errors", 0};
14791 char *encoding = NULL;
14792 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014793
Benjamin Peterson14339b62009-01-31 16:36:08 +000014794 if (type != &PyUnicode_Type)
14795 return unicode_subtype_new(type, args, kwds);
14796 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014797 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014798 return NULL;
14799 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014800 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014801 if (encoding == NULL && errors == NULL)
14802 return PyObject_Str(x);
14803 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014804 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014805}
14806
Guido van Rossume023fe02001-08-30 03:12:59 +000014807static PyObject *
14808unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14809{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014810 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014811 Py_ssize_t length, char_size;
14812 int share_wstr, share_utf8;
14813 unsigned int kind;
14814 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014815
Benjamin Peterson14339b62009-01-31 16:36:08 +000014816 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014817
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014818 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014819 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014820 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014821 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014822 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014823 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014824 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014825 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014826
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014827 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014828 if (self == NULL) {
14829 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014830 return NULL;
14831 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014832 kind = PyUnicode_KIND(unicode);
14833 length = PyUnicode_GET_LENGTH(unicode);
14834
14835 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014836#ifdef Py_DEBUG
14837 _PyUnicode_HASH(self) = -1;
14838#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014839 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014840#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014841 _PyUnicode_STATE(self).interned = 0;
14842 _PyUnicode_STATE(self).kind = kind;
14843 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014844 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014845 _PyUnicode_STATE(self).ready = 1;
14846 _PyUnicode_WSTR(self) = NULL;
14847 _PyUnicode_UTF8_LENGTH(self) = 0;
14848 _PyUnicode_UTF8(self) = NULL;
14849 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014850 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014851
14852 share_utf8 = 0;
14853 share_wstr = 0;
14854 if (kind == PyUnicode_1BYTE_KIND) {
14855 char_size = 1;
14856 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14857 share_utf8 = 1;
14858 }
14859 else if (kind == PyUnicode_2BYTE_KIND) {
14860 char_size = 2;
14861 if (sizeof(wchar_t) == 2)
14862 share_wstr = 1;
14863 }
14864 else {
14865 assert(kind == PyUnicode_4BYTE_KIND);
14866 char_size = 4;
14867 if (sizeof(wchar_t) == 4)
14868 share_wstr = 1;
14869 }
14870
14871 /* Ensure we won't overflow the length. */
14872 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14873 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014874 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014875 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014876 data = PyObject_MALLOC((length + 1) * char_size);
14877 if (data == NULL) {
14878 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014879 goto onError;
14880 }
14881
Victor Stinnerc3c74152011-10-02 20:39:55 +020014882 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014883 if (share_utf8) {
14884 _PyUnicode_UTF8_LENGTH(self) = length;
14885 _PyUnicode_UTF8(self) = data;
14886 }
14887 if (share_wstr) {
14888 _PyUnicode_WSTR_LENGTH(self) = length;
14889 _PyUnicode_WSTR(self) = (wchar_t *)data;
14890 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014891
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014892 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014893 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014894 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014895#ifdef Py_DEBUG
14896 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14897#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014898 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014899 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014900
14901onError:
14902 Py_DECREF(unicode);
14903 Py_DECREF(self);
14904 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014905}
14906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014907PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014908"str(object='') -> str\n\
14909str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014910\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014911Create a new string object from the given object. If encoding or\n\
14912errors is specified, then the object must expose a data buffer\n\
14913that will be decoded using the given encoding and error handler.\n\
14914Otherwise, returns the result of object.__str__() (if defined)\n\
14915or repr(object).\n\
14916encoding defaults to sys.getdefaultencoding().\n\
14917errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014918
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014919static PyObject *unicode_iter(PyObject *seq);
14920
Guido van Rossumd57fd912000-03-10 22:53:23 +000014921PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014922 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014923 "str", /* tp_name */
14924 sizeof(PyUnicodeObject), /* tp_size */
14925 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014927 (destructor)unicode_dealloc, /* tp_dealloc */
14928 0, /* tp_print */
14929 0, /* tp_getattr */
14930 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014931 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014932 unicode_repr, /* tp_repr */
14933 &unicode_as_number, /* tp_as_number */
14934 &unicode_as_sequence, /* tp_as_sequence */
14935 &unicode_as_mapping, /* tp_as_mapping */
14936 (hashfunc) unicode_hash, /* tp_hash*/
14937 0, /* tp_call*/
14938 (reprfunc) unicode_str, /* tp_str */
14939 PyObject_GenericGetAttr, /* tp_getattro */
14940 0, /* tp_setattro */
14941 0, /* tp_as_buffer */
14942 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014943 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014944 unicode_doc, /* tp_doc */
14945 0, /* tp_traverse */
14946 0, /* tp_clear */
14947 PyUnicode_RichCompare, /* tp_richcompare */
14948 0, /* tp_weaklistoffset */
14949 unicode_iter, /* tp_iter */
14950 0, /* tp_iternext */
14951 unicode_methods, /* tp_methods */
14952 0, /* tp_members */
14953 0, /* tp_getset */
14954 &PyBaseObject_Type, /* tp_base */
14955 0, /* tp_dict */
14956 0, /* tp_descr_get */
14957 0, /* tp_descr_set */
14958 0, /* tp_dictoffset */
14959 0, /* tp_init */
14960 0, /* tp_alloc */
14961 unicode_new, /* tp_new */
14962 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014963};
14964
14965/* Initialize the Unicode implementation */
14966
Victor Stinner3a50e702011-10-18 21:21:00 +020014967int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014968{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014969 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014970 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014971 0x000A, /* LINE FEED */
14972 0x000D, /* CARRIAGE RETURN */
14973 0x001C, /* FILE SEPARATOR */
14974 0x001D, /* GROUP SEPARATOR */
14975 0x001E, /* RECORD SEPARATOR */
14976 0x0085, /* NEXT LINE */
14977 0x2028, /* LINE SEPARATOR */
14978 0x2029, /* PARAGRAPH SEPARATOR */
14979 };
14980
Fred Drakee4315f52000-05-09 19:53:39 +000014981 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014982 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014983 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014984 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014985 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014986
Guido van Rossumcacfc072002-05-24 19:01:59 +000014987 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014988 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014989
14990 /* initialize the linebreak bloom filter */
14991 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014992 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014993 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014994
Christian Heimes26532f72013-07-20 14:57:16 +020014995 if (PyType_Ready(&EncodingMapType) < 0)
14996 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014997
Benjamin Petersonc4311282012-10-30 23:21:10 -040014998 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14999 Py_FatalError("Can't initialize field name iterator type");
15000
15001 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15002 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015003
Victor Stinner3a50e702011-10-18 21:21:00 +020015004#ifdef HAVE_MBCS
15005 winver.dwOSVersionInfoSize = sizeof(winver);
15006 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
15007 PyErr_SetFromWindowsErr(0);
15008 return -1;
15009 }
15010#endif
15011 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015012}
15013
15014/* Finalize the Unicode implementation */
15015
Christian Heimesa156e092008-02-16 07:38:31 +000015016int
15017PyUnicode_ClearFreeList(void)
15018{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015019 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015020}
15021
Guido van Rossumd57fd912000-03-10 22:53:23 +000015022void
Thomas Wouters78890102000-07-22 19:25:51 +000015023_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015024{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015025 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015026
Serhiy Storchaka05997252013-01-26 12:14:02 +020015027 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015028
Serhiy Storchaka05997252013-01-26 12:14:02 +020015029 for (i = 0; i < 256; i++)
15030 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015031 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015032 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015033}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015034
Walter Dörwald16807132007-05-25 13:52:07 +000015035void
15036PyUnicode_InternInPlace(PyObject **p)
15037{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015038 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015039 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015040#ifdef Py_DEBUG
15041 assert(s != NULL);
15042 assert(_PyUnicode_CHECK(s));
15043#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015045 return;
15046#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015047 /* If it's a subclass, we don't really know what putting
15048 it in the interned dict might do. */
15049 if (!PyUnicode_CheckExact(s))
15050 return;
15051 if (PyUnicode_CHECK_INTERNED(s))
15052 return;
15053 if (interned == NULL) {
15054 interned = PyDict_New();
15055 if (interned == NULL) {
15056 PyErr_Clear(); /* Don't leave an exception */
15057 return;
15058 }
15059 }
15060 /* It might be that the GetItem call fails even
15061 though the key is present in the dictionary,
15062 namely when this happens during a stack overflow. */
15063 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015064 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015065 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015066
Victor Stinnerf0335102013-04-14 19:13:03 +020015067 if (t) {
15068 Py_INCREF(t);
15069 Py_DECREF(*p);
15070 *p = t;
15071 return;
15072 }
Walter Dörwald16807132007-05-25 13:52:07 +000015073
Benjamin Peterson14339b62009-01-31 16:36:08 +000015074 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015075 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 PyErr_Clear();
15077 PyThreadState_GET()->recursion_critical = 0;
15078 return;
15079 }
15080 PyThreadState_GET()->recursion_critical = 0;
15081 /* The two references in interned are not counted by refcnt.
15082 The deallocator will take care of this */
15083 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015084 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015085}
15086
15087void
15088PyUnicode_InternImmortal(PyObject **p)
15089{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 PyUnicode_InternInPlace(p);
15091 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015092 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015093 Py_INCREF(*p);
15094 }
Walter Dörwald16807132007-05-25 13:52:07 +000015095}
15096
15097PyObject *
15098PyUnicode_InternFromString(const char *cp)
15099{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015100 PyObject *s = PyUnicode_FromString(cp);
15101 if (s == NULL)
15102 return NULL;
15103 PyUnicode_InternInPlace(&s);
15104 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015105}
15106
Alexander Belopolsky40018472011-02-26 01:02:56 +000015107void
15108_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015110 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015111 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 Py_ssize_t i, n;
15113 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015114
Benjamin Peterson14339b62009-01-31 16:36:08 +000015115 if (interned == NULL || !PyDict_Check(interned))
15116 return;
15117 keys = PyDict_Keys(interned);
15118 if (keys == NULL || !PyList_Check(keys)) {
15119 PyErr_Clear();
15120 return;
15121 }
Walter Dörwald16807132007-05-25 13:52:07 +000015122
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15124 detector, interned unicode strings are not forcibly deallocated;
15125 rather, we give them their stolen references back, and then clear
15126 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015127
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 n = PyList_GET_SIZE(keys);
15129 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015130 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015131 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015132 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015133 if (PyUnicode_READY(s) == -1) {
15134 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015135 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015137 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015138 case SSTATE_NOT_INTERNED:
15139 /* XXX Shouldn't happen */
15140 break;
15141 case SSTATE_INTERNED_IMMORTAL:
15142 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015143 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015144 break;
15145 case SSTATE_INTERNED_MORTAL:
15146 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015147 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 break;
15149 default:
15150 Py_FatalError("Inconsistent interned string state.");
15151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015152 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 }
15154 fprintf(stderr, "total size of all interned strings: "
15155 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15156 "mortal/immortal\n", mortal_size, immortal_size);
15157 Py_DECREF(keys);
15158 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015159 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015160}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015161
15162
15163/********************* Unicode Iterator **************************/
15164
15165typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015166 PyObject_HEAD
15167 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015168 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015169} unicodeiterobject;
15170
15171static void
15172unicodeiter_dealloc(unicodeiterobject *it)
15173{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015174 _PyObject_GC_UNTRACK(it);
15175 Py_XDECREF(it->it_seq);
15176 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015177}
15178
15179static int
15180unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15181{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015182 Py_VISIT(it->it_seq);
15183 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015184}
15185
15186static PyObject *
15187unicodeiter_next(unicodeiterobject *it)
15188{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015189 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015190
Benjamin Peterson14339b62009-01-31 16:36:08 +000015191 assert(it != NULL);
15192 seq = it->it_seq;
15193 if (seq == NULL)
15194 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015195 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015197 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15198 int kind = PyUnicode_KIND(seq);
15199 void *data = PyUnicode_DATA(seq);
15200 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15201 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 if (item != NULL)
15203 ++it->it_index;
15204 return item;
15205 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015206
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 Py_DECREF(seq);
15208 it->it_seq = NULL;
15209 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015210}
15211
15212static PyObject *
15213unicodeiter_len(unicodeiterobject *it)
15214{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 Py_ssize_t len = 0;
15216 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015217 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015218 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015219}
15220
15221PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15222
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015223static PyObject *
15224unicodeiter_reduce(unicodeiterobject *it)
15225{
15226 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015227 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015228 it->it_seq, it->it_index);
15229 } else {
15230 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15231 if (u == NULL)
15232 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015233 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015234 }
15235}
15236
15237PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15238
15239static PyObject *
15240unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15241{
15242 Py_ssize_t index = PyLong_AsSsize_t(state);
15243 if (index == -1 && PyErr_Occurred())
15244 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015245 if (it->it_seq != NULL) {
15246 if (index < 0)
15247 index = 0;
15248 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15249 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15250 it->it_index = index;
15251 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015252 Py_RETURN_NONE;
15253}
15254
15255PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15256
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015257static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015258 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015259 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015260 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15261 reduce_doc},
15262 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15263 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015264 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015265};
15266
15267PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15269 "str_iterator", /* tp_name */
15270 sizeof(unicodeiterobject), /* tp_basicsize */
15271 0, /* tp_itemsize */
15272 /* methods */
15273 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15274 0, /* tp_print */
15275 0, /* tp_getattr */
15276 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015277 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 0, /* tp_repr */
15279 0, /* tp_as_number */
15280 0, /* tp_as_sequence */
15281 0, /* tp_as_mapping */
15282 0, /* tp_hash */
15283 0, /* tp_call */
15284 0, /* tp_str */
15285 PyObject_GenericGetAttr, /* tp_getattro */
15286 0, /* tp_setattro */
15287 0, /* tp_as_buffer */
15288 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15289 0, /* tp_doc */
15290 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15291 0, /* tp_clear */
15292 0, /* tp_richcompare */
15293 0, /* tp_weaklistoffset */
15294 PyObject_SelfIter, /* tp_iter */
15295 (iternextfunc)unicodeiter_next, /* tp_iternext */
15296 unicodeiter_methods, /* tp_methods */
15297 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015298};
15299
15300static PyObject *
15301unicode_iter(PyObject *seq)
15302{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015303 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015304
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 if (!PyUnicode_Check(seq)) {
15306 PyErr_BadInternalCall();
15307 return NULL;
15308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015309 if (PyUnicode_READY(seq) == -1)
15310 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015311 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15312 if (it == NULL)
15313 return NULL;
15314 it->it_index = 0;
15315 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015316 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015317 _PyObject_GC_TRACK(it);
15318 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015319}
15320
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015321
15322size_t
15323Py_UNICODE_strlen(const Py_UNICODE *u)
15324{
15325 int res = 0;
15326 while(*u++)
15327 res++;
15328 return res;
15329}
15330
15331Py_UNICODE*
15332Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15333{
15334 Py_UNICODE *u = s1;
15335 while ((*u++ = *s2++));
15336 return s1;
15337}
15338
15339Py_UNICODE*
15340Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15341{
15342 Py_UNICODE *u = s1;
15343 while ((*u++ = *s2++))
15344 if (n-- == 0)
15345 break;
15346 return s1;
15347}
15348
15349Py_UNICODE*
15350Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15351{
15352 Py_UNICODE *u1 = s1;
15353 u1 += Py_UNICODE_strlen(u1);
15354 Py_UNICODE_strcpy(u1, s2);
15355 return s1;
15356}
15357
15358int
15359Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15360{
15361 while (*s1 && *s2 && *s1 == *s2)
15362 s1++, s2++;
15363 if (*s1 && *s2)
15364 return (*s1 < *s2) ? -1 : +1;
15365 if (*s1)
15366 return 1;
15367 if (*s2)
15368 return -1;
15369 return 0;
15370}
15371
15372int
15373Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15374{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015375 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015376 for (; n != 0; n--) {
15377 u1 = *s1;
15378 u2 = *s2;
15379 if (u1 != u2)
15380 return (u1 < u2) ? -1 : +1;
15381 if (u1 == '\0')
15382 return 0;
15383 s1++;
15384 s2++;
15385 }
15386 return 0;
15387}
15388
15389Py_UNICODE*
15390Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15391{
15392 const Py_UNICODE *p;
15393 for (p = s; *p; p++)
15394 if (*p == c)
15395 return (Py_UNICODE*)p;
15396 return NULL;
15397}
15398
15399Py_UNICODE*
15400Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15401{
15402 const Py_UNICODE *p;
15403 p = s + Py_UNICODE_strlen(s);
15404 while (p != s) {
15405 p--;
15406 if (*p == c)
15407 return (Py_UNICODE*)p;
15408 }
15409 return NULL;
15410}
Victor Stinner331ea922010-08-10 16:37:20 +000015411
Victor Stinner71133ff2010-09-01 23:43:53 +000015412Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015413PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015414{
Victor Stinner577db2c2011-10-11 22:12:48 +020015415 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015416 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015418 if (!PyUnicode_Check(unicode)) {
15419 PyErr_BadArgument();
15420 return NULL;
15421 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015422 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015423 if (u == NULL)
15424 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015425 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015426 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015427 PyErr_NoMemory();
15428 return NULL;
15429 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015430 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015431 size *= sizeof(Py_UNICODE);
15432 copy = PyMem_Malloc(size);
15433 if (copy == NULL) {
15434 PyErr_NoMemory();
15435 return NULL;
15436 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015437 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015438 return copy;
15439}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015440
Georg Brandl66c221e2010-10-14 07:04:07 +000015441/* A _string module, to export formatter_parser and formatter_field_name_split
15442 to the string.Formatter class implemented in Python. */
15443
15444static PyMethodDef _string_methods[] = {
15445 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15446 METH_O, PyDoc_STR("split the argument as a field name")},
15447 {"formatter_parser", (PyCFunction) formatter_parser,
15448 METH_O, PyDoc_STR("parse the argument as a format string")},
15449 {NULL, NULL}
15450};
15451
15452static struct PyModuleDef _string_module = {
15453 PyModuleDef_HEAD_INIT,
15454 "_string",
15455 PyDoc_STR("string helper module"),
15456 0,
15457 _string_methods,
15458 NULL,
15459 NULL,
15460 NULL,
15461 NULL
15462};
15463
15464PyMODINIT_FUNC
15465PyInit__string(void)
15466{
15467 return PyModule_Create(&_string_module);
15468}
15469
15470
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015471#ifdef __cplusplus
15472}
15473#endif