blob: ab22289f5066e8a331e5f617449028d0e26e8ca6 [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
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522/* --- Bloom Filters ----------------------------------------------------- */
523
524/* stuff to implement simple "bloom filters" for Unicode characters.
525 to keep things simple, we use a single bitmask, using the least 5
526 bits from each unicode characters as the bit index. */
527
528/* the linebreak mask is set up by Unicode_Init below */
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#if LONG_BIT >= 128
531#define BLOOM_WIDTH 128
532#elif LONG_BIT >= 64
533#define BLOOM_WIDTH 64
534#elif LONG_BIT >= 32
535#define BLOOM_WIDTH 32
536#else
537#error "LONG_BIT is smaller than 32"
538#endif
539
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540#define BLOOM_MASK unsigned long
541
Serhiy Storchaka05997252013-01-26 12:14:02 +0200542static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
Antoine Pitrouf068f942010-01-13 14:19:12 +0000544#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545
Benjamin Peterson29060642009-01-31 22:14:21 +0000546#define BLOOM_LINEBREAK(ch) \
547 ((ch) < 128U ? ascii_linebreak[(ch)] : \
548 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549
Alexander Belopolsky40018472011-02-26 01:02:56 +0000550Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200551make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552{
Victor Stinnera85af502013-04-09 21:53:54 +0200553#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
554 do { \
555 TYPE *data = (TYPE *)PTR; \
556 TYPE *end = data + LEN; \
557 Py_UCS4 ch; \
558 for (; data != end; data++) { \
559 ch = *data; \
560 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
561 } \
562 break; \
563 } while (0)
564
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 /* calculate simple bloom-style bitmask for a given unicode string */
566
Antoine Pitrouf068f942010-01-13 14:19:12 +0000567 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568
569 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200570 switch (kind) {
571 case PyUnicode_1BYTE_KIND:
572 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
573 break;
574 case PyUnicode_2BYTE_KIND:
575 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
576 break;
577 case PyUnicode_4BYTE_KIND:
578 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
579 break;
580 default:
581 assert(0);
582 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200584
585#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586}
587
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200588/* Compilation of templated routines */
589
590#include "stringlib/asciilib.h"
591#include "stringlib/fastsearch.h"
592#include "stringlib/partition.h"
593#include "stringlib/split.h"
594#include "stringlib/count.h"
595#include "stringlib/find.h"
596#include "stringlib/find_max_char.h"
597#include "stringlib/localeutil.h"
598#include "stringlib/undef.h"
599
600#include "stringlib/ucs1lib.h"
601#include "stringlib/fastsearch.h"
602#include "stringlib/partition.h"
603#include "stringlib/split.h"
604#include "stringlib/count.h"
605#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300606#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200607#include "stringlib/find_max_char.h"
608#include "stringlib/localeutil.h"
609#include "stringlib/undef.h"
610
611#include "stringlib/ucs2lib.h"
612#include "stringlib/fastsearch.h"
613#include "stringlib/partition.h"
614#include "stringlib/split.h"
615#include "stringlib/count.h"
616#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300617#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200618#include "stringlib/find_max_char.h"
619#include "stringlib/localeutil.h"
620#include "stringlib/undef.h"
621
622#include "stringlib/ucs4lib.h"
623#include "stringlib/fastsearch.h"
624#include "stringlib/partition.h"
625#include "stringlib/split.h"
626#include "stringlib/count.h"
627#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300628#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200629#include "stringlib/find_max_char.h"
630#include "stringlib/localeutil.h"
631#include "stringlib/undef.h"
632
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200633#include "stringlib/unicodedefs.h"
634#include "stringlib/fastsearch.h"
635#include "stringlib/count.h"
636#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100637#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200638
Guido van Rossumd57fd912000-03-10 22:53:23 +0000639/* --- Unicode Object ----------------------------------------------------- */
640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200642fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200643
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200644Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
645 Py_ssize_t size, Py_UCS4 ch,
646 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200647{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
649
650 switch (kind) {
651 case PyUnicode_1BYTE_KIND:
652 {
653 Py_UCS1 ch1 = (Py_UCS1) ch;
654 if (ch1 == ch)
655 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
656 else
657 return -1;
658 }
659 case PyUnicode_2BYTE_KIND:
660 {
661 Py_UCS2 ch2 = (Py_UCS2) ch;
662 if (ch2 == ch)
663 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
664 else
665 return -1;
666 }
667 case PyUnicode_4BYTE_KIND:
668 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
669 default:
670 assert(0);
671 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200672 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200673}
674
Victor Stinnerafffce42012-10-03 23:03:17 +0200675#ifdef Py_DEBUG
676/* Fill the data of an Unicode string with invalid characters to detect bugs
677 earlier.
678
679 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
680 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
681 invalid character in Unicode 6.0. */
682static void
683unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
684{
685 int kind = PyUnicode_KIND(unicode);
686 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
687 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
688 if (length <= old_length)
689 return;
690 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
691}
692#endif
693
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694static PyObject*
695resize_compact(PyObject *unicode, Py_ssize_t length)
696{
697 Py_ssize_t char_size;
698 Py_ssize_t struct_size;
699 Py_ssize_t new_size;
700 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100701 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200702#ifdef Py_DEBUG
703 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
704#endif
705
Victor Stinner79891572012-05-03 13:43:07 +0200706 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200707 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100708 assert(PyUnicode_IS_COMPACT(unicode));
709
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200710 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100711 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200712 struct_size = sizeof(PyASCIIObject);
713 else
714 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200715 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200716
Victor Stinnerfe226c02011-10-03 03:52:20 +0200717 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
718 PyErr_NoMemory();
719 return NULL;
720 }
721 new_size = (struct_size + (length + 1) * char_size);
722
Victor Stinner84def372011-12-11 20:04:56 +0100723 _Py_DEC_REFTOTAL;
724 _Py_ForgetReference(unicode);
725
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300726 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100727 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100728 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200729 PyErr_NoMemory();
730 return NULL;
731 }
Victor Stinner84def372011-12-11 20:04:56 +0100732 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200733 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100734
Victor Stinnerfe226c02011-10-03 03:52:20 +0200735 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200736 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100738 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200739 _PyUnicode_WSTR_LENGTH(unicode) = length;
740 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100741 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
742 PyObject_DEL(_PyUnicode_WSTR(unicode));
743 _PyUnicode_WSTR(unicode) = NULL;
744 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200745#ifdef Py_DEBUG
746 unicode_fill_invalid(unicode, old_length);
747#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200748 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
749 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200750 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200751 return unicode;
752}
753
Alexander Belopolsky40018472011-02-26 01:02:56 +0000754static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200755resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000756{
Victor Stinner95663112011-10-04 01:03:50 +0200757 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100758 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200759 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000761
Victor Stinnerfe226c02011-10-03 03:52:20 +0200762 if (PyUnicode_IS_READY(unicode)) {
763 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200764 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200766#ifdef Py_DEBUG
767 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
768#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200771 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200772 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
773 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200774
775 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
776 PyErr_NoMemory();
777 return -1;
778 }
779 new_size = (length + 1) * char_size;
780
Victor Stinner7a9105a2011-12-12 00:13:42 +0100781 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
782 {
783 PyObject_DEL(_PyUnicode_UTF8(unicode));
784 _PyUnicode_UTF8(unicode) = NULL;
785 _PyUnicode_UTF8_LENGTH(unicode) = 0;
786 }
787
Victor Stinnerfe226c02011-10-03 03:52:20 +0200788 data = (PyObject *)PyObject_REALLOC(data, new_size);
789 if (data == NULL) {
790 PyErr_NoMemory();
791 return -1;
792 }
793 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200794 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200795 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200796 _PyUnicode_WSTR_LENGTH(unicode) = length;
797 }
798 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200799 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200800 _PyUnicode_UTF8_LENGTH(unicode) = length;
801 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200802 _PyUnicode_LENGTH(unicode) = length;
803 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200804#ifdef Py_DEBUG
805 unicode_fill_invalid(unicode, old_length);
806#endif
Victor Stinner95663112011-10-04 01:03:50 +0200807 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200808 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200809 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200810 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200811 }
Victor Stinner95663112011-10-04 01:03:50 +0200812 assert(_PyUnicode_WSTR(unicode) != NULL);
813
814 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700815 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200816 PyErr_NoMemory();
817 return -1;
818 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100819 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200820 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100821 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200822 if (!wstr) {
823 PyErr_NoMemory();
824 return -1;
825 }
826 _PyUnicode_WSTR(unicode) = wstr;
827 _PyUnicode_WSTR(unicode)[length] = 0;
828 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200829 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000830 return 0;
831}
832
Victor Stinnerfe226c02011-10-03 03:52:20 +0200833static PyObject*
834resize_copy(PyObject *unicode, Py_ssize_t length)
835{
836 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100837 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200838 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100839
Benjamin Petersonbac79492012-01-14 13:34:47 -0500840 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100841 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200842
843 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
844 if (copy == NULL)
845 return NULL;
846
847 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200848 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200849 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200850 }
851 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200852 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100853
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200854 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200855 if (w == NULL)
856 return NULL;
857 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
858 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200859 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
860 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200861 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200862 }
863}
864
Guido van Rossumd57fd912000-03-10 22:53:23 +0000865/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000866 Ux0000 terminated; some code (e.g. new_identifier)
867 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000868
869 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000870 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000871
872*/
873
Alexander Belopolsky40018472011-02-26 01:02:56 +0000874static PyUnicodeObject *
875_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000876{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200877 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200878 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000879
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000881 if (length == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000884 }
885
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000886 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700887 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000888 return (PyUnicodeObject *)PyErr_NoMemory();
889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200890 if (length < 0) {
891 PyErr_SetString(PyExc_SystemError,
892 "Negative size passed to _PyUnicode_New");
893 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000894 }
895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
897 if (unicode == NULL)
898 return NULL;
899 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100900
901 _PyUnicode_WSTR_LENGTH(unicode) = length;
902 _PyUnicode_HASH(unicode) = -1;
903 _PyUnicode_STATE(unicode).interned = 0;
904 _PyUnicode_STATE(unicode).kind = 0;
905 _PyUnicode_STATE(unicode).compact = 0;
906 _PyUnicode_STATE(unicode).ready = 0;
907 _PyUnicode_STATE(unicode).ascii = 0;
908 _PyUnicode_DATA_ANY(unicode) = NULL;
909 _PyUnicode_LENGTH(unicode) = 0;
910 _PyUnicode_UTF8(unicode) = NULL;
911 _PyUnicode_UTF8_LENGTH(unicode) = 0;
912
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
914 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100915 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000916 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100917 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000918 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200919
Jeremy Hyltond8082792003-09-16 19:41:39 +0000920 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000921 * the caller fails before initializing str -- unicode_resize()
922 * reads str[0], and the Keep-Alive optimization can keep memory
923 * allocated for str alive across a call to unicode_dealloc(unicode).
924 * We don't want unicode_resize to read uninitialized memory in
925 * that case.
926 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200927 _PyUnicode_WSTR(unicode)[0] = 0;
928 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100929
Victor Stinner7931d9a2011-11-04 00:22:48 +0100930 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000931 return unicode;
932}
933
Victor Stinnerf42dc442011-10-02 23:33:16 +0200934static const char*
935unicode_kind_name(PyObject *unicode)
936{
Victor Stinner42dfd712011-10-03 14:41:45 +0200937 /* don't check consistency: unicode_kind_name() is called from
938 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200939 if (!PyUnicode_IS_COMPACT(unicode))
940 {
941 if (!PyUnicode_IS_READY(unicode))
942 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600943 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200944 {
945 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200946 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200947 return "legacy ascii";
948 else
949 return "legacy latin1";
950 case PyUnicode_2BYTE_KIND:
951 return "legacy UCS2";
952 case PyUnicode_4BYTE_KIND:
953 return "legacy UCS4";
954 default:
955 return "<legacy invalid kind>";
956 }
957 }
958 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600959 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200960 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200961 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200962 return "ascii";
963 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200966 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200967 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200968 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200969 default:
970 return "<invalid compact kind>";
971 }
972}
973
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975/* Functions wrapping macros for use in debugger */
976char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200977 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978}
979
980void *_PyUnicode_compact_data(void *unicode) {
981 return _PyUnicode_COMPACT_DATA(unicode);
982}
983void *_PyUnicode_data(void *unicode){
984 printf("obj %p\n", unicode);
985 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
986 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
987 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
988 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
989 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
990 return PyUnicode_DATA(unicode);
991}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200992
993void
994_PyUnicode_Dump(PyObject *op)
995{
996 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200997 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
998 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
999 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001000
Victor Stinnera849a4b2011-10-03 12:12:11 +02001001 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001002 {
1003 if (ascii->state.ascii)
1004 data = (ascii + 1);
1005 else
1006 data = (compact + 1);
1007 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001008 else
1009 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001010 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1011 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001012
Victor Stinnera849a4b2011-10-03 12:12:11 +02001013 if (ascii->wstr == data)
1014 printf("shared ");
1015 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001016
Victor Stinnera3b334d2011-10-03 13:53:37 +02001017 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001018 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001019 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1020 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001021 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1022 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001023 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001024 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001025}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001026#endif
1027
1028PyObject *
1029PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1030{
1031 PyObject *obj;
1032 PyCompactUnicodeObject *unicode;
1033 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001034 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001035 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001036 Py_ssize_t char_size;
1037 Py_ssize_t struct_size;
1038
1039 /* Optimization for empty strings */
1040 if (size == 0 && unicode_empty != NULL) {
1041 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001042 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043 }
1044
Victor Stinner9e9d6892011-10-04 01:02:02 +02001045 is_ascii = 0;
1046 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047 struct_size = sizeof(PyCompactUnicodeObject);
1048 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001049 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 char_size = 1;
1051 is_ascii = 1;
1052 struct_size = sizeof(PyASCIIObject);
1053 }
1054 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001055 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 char_size = 1;
1057 }
1058 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001059 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060 char_size = 2;
1061 if (sizeof(wchar_t) == 2)
1062 is_sharing = 1;
1063 }
1064 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001065 if (maxchar > MAX_UNICODE) {
1066 PyErr_SetString(PyExc_SystemError,
1067 "invalid maximum character passed to PyUnicode_New");
1068 return NULL;
1069 }
Victor Stinner8f825062012-04-27 13:55:39 +02001070 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 char_size = 4;
1072 if (sizeof(wchar_t) == 4)
1073 is_sharing = 1;
1074 }
1075
1076 /* Ensure we won't overflow the size. */
1077 if (size < 0) {
1078 PyErr_SetString(PyExc_SystemError,
1079 "Negative size passed to PyUnicode_New");
1080 return NULL;
1081 }
1082 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1083 return PyErr_NoMemory();
1084
1085 /* Duplicated allocation code from _PyObject_New() instead of a call to
1086 * PyObject_New() so we are able to allocate space for the object and
1087 * it's data buffer.
1088 */
1089 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1090 if (obj == NULL)
1091 return PyErr_NoMemory();
1092 obj = PyObject_INIT(obj, &PyUnicode_Type);
1093 if (obj == NULL)
1094 return NULL;
1095
1096 unicode = (PyCompactUnicodeObject *)obj;
1097 if (is_ascii)
1098 data = ((PyASCIIObject*)obj) + 1;
1099 else
1100 data = unicode + 1;
1101 _PyUnicode_LENGTH(unicode) = size;
1102 _PyUnicode_HASH(unicode) = -1;
1103 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001104 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 _PyUnicode_STATE(unicode).compact = 1;
1106 _PyUnicode_STATE(unicode).ready = 1;
1107 _PyUnicode_STATE(unicode).ascii = is_ascii;
1108 if (is_ascii) {
1109 ((char*)data)[size] = 0;
1110 _PyUnicode_WSTR(unicode) = NULL;
1111 }
Victor Stinner8f825062012-04-27 13:55:39 +02001112 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001113 ((char*)data)[size] = 0;
1114 _PyUnicode_WSTR(unicode) = NULL;
1115 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001117 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 else {
1120 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001121 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001122 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001123 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001124 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 ((Py_UCS4*)data)[size] = 0;
1126 if (is_sharing) {
1127 _PyUnicode_WSTR_LENGTH(unicode) = size;
1128 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1129 }
1130 else {
1131 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1132 _PyUnicode_WSTR(unicode) = NULL;
1133 }
1134 }
Victor Stinner8f825062012-04-27 13:55:39 +02001135#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001136 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001137#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001138 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139 return obj;
1140}
1141
1142#if SIZEOF_WCHAR_T == 2
1143/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1144 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001145 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001146
1147 This function assumes that unicode can hold one more code point than wstr
1148 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001149static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001151 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001152{
1153 const wchar_t *iter;
1154 Py_UCS4 *ucs4_out;
1155
Victor Stinner910337b2011-10-03 03:20:16 +02001156 assert(unicode != NULL);
1157 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001158 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1159 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1160
1161 for (iter = begin; iter < end; ) {
1162 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1163 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001164 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1165 && (iter+1) < end
1166 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001167 {
Victor Stinner551ac952011-11-29 22:58:13 +01001168 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001169 iter += 2;
1170 }
1171 else {
1172 *ucs4_out++ = *iter;
1173 iter++;
1174 }
1175 }
1176 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1177 _PyUnicode_GET_LENGTH(unicode)));
1178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001179}
1180#endif
1181
Victor Stinnercd9950f2011-10-02 00:34:53 +02001182static int
Victor Stinner488fa492011-12-12 00:01:39 +01001183unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001184{
Victor Stinner488fa492011-12-12 00:01:39 +01001185 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001186 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001187 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001188 return -1;
1189 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001190 return 0;
1191}
1192
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001193static int
1194_copy_characters(PyObject *to, Py_ssize_t to_start,
1195 PyObject *from, Py_ssize_t from_start,
1196 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001197{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001198 unsigned int from_kind, to_kind;
1199 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200
Victor Stinneree4544c2012-05-09 22:24:08 +02001201 assert(0 <= how_many);
1202 assert(0 <= from_start);
1203 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001204 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001205 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001206 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207
Victor Stinnerd3f08822012-05-29 12:57:52 +02001208 assert(PyUnicode_Check(to));
1209 assert(PyUnicode_IS_READY(to));
1210 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1211
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001212 if (how_many == 0)
1213 return 0;
1214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001216 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219
Victor Stinnerf1852262012-06-16 16:38:26 +02001220#ifdef Py_DEBUG
1221 if (!check_maxchar
1222 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1223 {
1224 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1225 Py_UCS4 ch;
1226 Py_ssize_t i;
1227 for (i=0; i < how_many; i++) {
1228 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1229 assert(ch <= to_maxchar);
1230 }
1231 }
1232#endif
1233
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001234 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001235 if (check_maxchar
1236 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1237 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001238 /* Writing Latin-1 characters into an ASCII string requires to
1239 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001240 Py_UCS4 max_char;
1241 max_char = ucs1lib_find_max_char(from_data,
1242 (Py_UCS1*)from_data + how_many);
1243 if (max_char >= 128)
1244 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001245 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001246 Py_MEMCPY((char*)to_data + to_kind * to_start,
1247 (char*)from_data + from_kind * from_start,
1248 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001249 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001250 else if (from_kind == PyUnicode_1BYTE_KIND
1251 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001252 {
1253 _PyUnicode_CONVERT_BYTES(
1254 Py_UCS1, Py_UCS2,
1255 PyUnicode_1BYTE_DATA(from) + from_start,
1256 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1257 PyUnicode_2BYTE_DATA(to) + to_start
1258 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001259 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001260 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001261 && to_kind == PyUnicode_4BYTE_KIND)
1262 {
1263 _PyUnicode_CONVERT_BYTES(
1264 Py_UCS1, Py_UCS4,
1265 PyUnicode_1BYTE_DATA(from) + from_start,
1266 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1267 PyUnicode_4BYTE_DATA(to) + to_start
1268 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001269 }
1270 else if (from_kind == PyUnicode_2BYTE_KIND
1271 && to_kind == PyUnicode_4BYTE_KIND)
1272 {
1273 _PyUnicode_CONVERT_BYTES(
1274 Py_UCS2, Py_UCS4,
1275 PyUnicode_2BYTE_DATA(from) + from_start,
1276 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1277 PyUnicode_4BYTE_DATA(to) + to_start
1278 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001279 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001280 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001281 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1282
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001283 if (!check_maxchar) {
1284 if (from_kind == PyUnicode_2BYTE_KIND
1285 && to_kind == PyUnicode_1BYTE_KIND)
1286 {
1287 _PyUnicode_CONVERT_BYTES(
1288 Py_UCS2, Py_UCS1,
1289 PyUnicode_2BYTE_DATA(from) + from_start,
1290 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1291 PyUnicode_1BYTE_DATA(to) + to_start
1292 );
1293 }
1294 else if (from_kind == PyUnicode_4BYTE_KIND
1295 && to_kind == PyUnicode_1BYTE_KIND)
1296 {
1297 _PyUnicode_CONVERT_BYTES(
1298 Py_UCS4, Py_UCS1,
1299 PyUnicode_4BYTE_DATA(from) + from_start,
1300 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1301 PyUnicode_1BYTE_DATA(to) + to_start
1302 );
1303 }
1304 else if (from_kind == PyUnicode_4BYTE_KIND
1305 && to_kind == PyUnicode_2BYTE_KIND)
1306 {
1307 _PyUnicode_CONVERT_BYTES(
1308 Py_UCS4, Py_UCS2,
1309 PyUnicode_4BYTE_DATA(from) + from_start,
1310 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1311 PyUnicode_2BYTE_DATA(to) + to_start
1312 );
1313 }
1314 else {
1315 assert(0);
1316 return -1;
1317 }
1318 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001319 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001320 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001321 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001322 Py_ssize_t i;
1323
Victor Stinnera0702ab2011-09-29 14:14:38 +02001324 for (i=0; i < how_many; i++) {
1325 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001326 if (ch > to_maxchar)
1327 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001328 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1329 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001330 }
1331 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001332 return 0;
1333}
1334
Victor Stinnerd3f08822012-05-29 12:57:52 +02001335void
1336_PyUnicode_FastCopyCharacters(
1337 PyObject *to, Py_ssize_t to_start,
1338 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001339{
1340 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1341}
1342
1343Py_ssize_t
1344PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1345 PyObject *from, Py_ssize_t from_start,
1346 Py_ssize_t how_many)
1347{
1348 int err;
1349
1350 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1351 PyErr_BadInternalCall();
1352 return -1;
1353 }
1354
Benjamin Petersonbac79492012-01-14 13:34:47 -05001355 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001356 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001357 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001358 return -1;
1359
Victor Stinnerd3f08822012-05-29 12:57:52 +02001360 if (from_start < 0) {
1361 PyErr_SetString(PyExc_IndexError, "string index out of range");
1362 return -1;
1363 }
1364 if (to_start < 0) {
1365 PyErr_SetString(PyExc_IndexError, "string index out of range");
1366 return -1;
1367 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001368 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1369 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1370 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001371 "Cannot write %zi characters at %zi "
1372 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001373 how_many, to_start, PyUnicode_GET_LENGTH(to));
1374 return -1;
1375 }
1376
1377 if (how_many == 0)
1378 return 0;
1379
Victor Stinner488fa492011-12-12 00:01:39 +01001380 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001381 return -1;
1382
1383 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1384 if (err) {
1385 PyErr_Format(PyExc_SystemError,
1386 "Cannot copy %s characters "
1387 "into a string of %s characters",
1388 unicode_kind_name(from),
1389 unicode_kind_name(to));
1390 return -1;
1391 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001392 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393}
1394
Victor Stinner17222162011-09-28 22:15:37 +02001395/* Find the maximum code point and count the number of surrogate pairs so a
1396 correct string length can be computed before converting a string to UCS4.
1397 This function counts single surrogates as a character and not as a pair.
1398
1399 Return 0 on success, or -1 on error. */
1400static int
1401find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1402 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403{
1404 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001405 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406
Victor Stinnerc53be962011-10-02 21:33:54 +02001407 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408 *num_surrogates = 0;
1409 *maxchar = 0;
1410
1411 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001413 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1414 && (iter+1) < end
1415 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1416 {
1417 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1418 ++(*num_surrogates);
1419 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001420 }
1421 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001422#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001423 {
1424 ch = *iter;
1425 iter++;
1426 }
1427 if (ch > *maxchar) {
1428 *maxchar = ch;
1429 if (*maxchar > MAX_UNICODE) {
1430 PyErr_Format(PyExc_ValueError,
1431 "character U+%x is not in range [U+0000; U+10ffff]",
1432 ch);
1433 return -1;
1434 }
1435 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001436 }
1437 return 0;
1438}
1439
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001440int
1441_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442{
1443 wchar_t *end;
1444 Py_UCS4 maxchar = 0;
1445 Py_ssize_t num_surrogates;
1446#if SIZEOF_WCHAR_T == 2
1447 Py_ssize_t length_wo_surrogates;
1448#endif
1449
Georg Brandl7597add2011-10-05 16:36:47 +02001450 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001451 strings were created using _PyObject_New() and where no canonical
1452 representation (the str field) has been set yet aka strings
1453 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001454 assert(_PyUnicode_CHECK(unicode));
1455 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001457 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001458 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001459 /* Actually, it should neither be interned nor be anything else: */
1460 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001463 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001464 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466
1467 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1469 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 PyErr_NoMemory();
1471 return -1;
1472 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001473 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 _PyUnicode_WSTR(unicode), end,
1475 PyUnicode_1BYTE_DATA(unicode));
1476 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1477 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1478 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1479 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001480 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001481 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001482 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001483 }
1484 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001485 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001486 _PyUnicode_UTF8(unicode) = NULL;
1487 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001488 }
1489 PyObject_FREE(_PyUnicode_WSTR(unicode));
1490 _PyUnicode_WSTR(unicode) = NULL;
1491 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1492 }
1493 /* In this case we might have to convert down from 4-byte native
1494 wchar_t to 2-byte unicode. */
1495 else if (maxchar < 65536) {
1496 assert(num_surrogates == 0 &&
1497 "FindMaxCharAndNumSurrogatePairs() messed up");
1498
Victor Stinner506f5922011-09-28 22:34:18 +02001499#if SIZEOF_WCHAR_T == 2
1500 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001501 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001502 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1503 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1504 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001505 _PyUnicode_UTF8(unicode) = NULL;
1506 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001507#else
1508 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001509 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001510 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001511 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001512 PyErr_NoMemory();
1513 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001514 }
Victor Stinner506f5922011-09-28 22:34:18 +02001515 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1516 _PyUnicode_WSTR(unicode), end,
1517 PyUnicode_2BYTE_DATA(unicode));
1518 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1519 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1520 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001521 _PyUnicode_UTF8(unicode) = NULL;
1522 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001523 PyObject_FREE(_PyUnicode_WSTR(unicode));
1524 _PyUnicode_WSTR(unicode) = NULL;
1525 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1526#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001527 }
1528 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1529 else {
1530#if SIZEOF_WCHAR_T == 2
1531 /* in case the native representation is 2-bytes, we need to allocate a
1532 new normalized 4-byte version. */
1533 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001534 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1535 PyErr_NoMemory();
1536 return -1;
1537 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001538 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1539 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540 PyErr_NoMemory();
1541 return -1;
1542 }
1543 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1544 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001545 _PyUnicode_UTF8(unicode) = NULL;
1546 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001547 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1548 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001549 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550 PyObject_FREE(_PyUnicode_WSTR(unicode));
1551 _PyUnicode_WSTR(unicode) = NULL;
1552 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1553#else
1554 assert(num_surrogates == 0);
1555
Victor Stinnerc3c74152011-10-02 20:39:55 +02001556 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001557 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001558 _PyUnicode_UTF8(unicode) = NULL;
1559 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1561#endif
1562 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1563 }
1564 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 return 0;
1567}
1568
Alexander Belopolsky40018472011-02-26 01:02:56 +00001569static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001570unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001571{
Walter Dörwald16807132007-05-25 13:52:07 +00001572 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001573 case SSTATE_NOT_INTERNED:
1574 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001575
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_INTERNED_MORTAL:
1577 /* revive dead object temporarily for DelItem */
1578 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001579 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001580 Py_FatalError(
1581 "deletion of interned string failed");
1582 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001583
Benjamin Peterson29060642009-01-31 22:14:21 +00001584 case SSTATE_INTERNED_IMMORTAL:
1585 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 default:
1588 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589 }
1590
Victor Stinner03490912011-10-03 23:45:12 +02001591 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001593 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001594 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001595 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1596 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001599}
1600
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601#ifdef Py_DEBUG
1602static int
1603unicode_is_singleton(PyObject *unicode)
1604{
1605 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1606 if (unicode == unicode_empty)
1607 return 1;
1608 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1609 {
1610 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1611 if (ch < 256 && unicode_latin1[ch] == unicode)
1612 return 1;
1613 }
1614 return 0;
1615}
1616#endif
1617
Alexander Belopolsky40018472011-02-26 01:02:56 +00001618static int
Victor Stinner488fa492011-12-12 00:01:39 +01001619unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620{
Victor Stinner488fa492011-12-12 00:01:39 +01001621 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001622 if (Py_REFCNT(unicode) != 1)
1623 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001624 if (_PyUnicode_HASH(unicode) != -1)
1625 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001626 if (PyUnicode_CHECK_INTERNED(unicode))
1627 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001628 if (!PyUnicode_CheckExact(unicode))
1629 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001630#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001631 /* singleton refcount is greater than 1 */
1632 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001634 return 1;
1635}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001636
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637static int
1638unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1639{
1640 PyObject *unicode;
1641 Py_ssize_t old_length;
1642
1643 assert(p_unicode != NULL);
1644 unicode = *p_unicode;
1645
1646 assert(unicode != NULL);
1647 assert(PyUnicode_Check(unicode));
1648 assert(0 <= length);
1649
Victor Stinner910337b2011-10-03 03:20:16 +02001650 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001651 old_length = PyUnicode_WSTR_LENGTH(unicode);
1652 else
1653 old_length = PyUnicode_GET_LENGTH(unicode);
1654 if (old_length == length)
1655 return 0;
1656
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001657 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001658 _Py_INCREF_UNICODE_EMPTY();
1659 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001660 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001661 Py_DECREF(*p_unicode);
1662 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001663 return 0;
1664 }
1665
Victor Stinner488fa492011-12-12 00:01:39 +01001666 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001667 PyObject *copy = resize_copy(unicode, length);
1668 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001669 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 Py_DECREF(*p_unicode);
1671 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001673 }
1674
Victor Stinnerfe226c02011-10-03 03:52:20 +02001675 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001676 PyObject *new_unicode = resize_compact(unicode, length);
1677 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001680 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001681 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001682 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001683}
1684
Alexander Belopolsky40018472011-02-26 01:02:56 +00001685int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001686PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001687{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001688 PyObject *unicode;
1689 if (p_unicode == NULL) {
1690 PyErr_BadInternalCall();
1691 return -1;
1692 }
1693 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001694 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001695 {
1696 PyErr_BadInternalCall();
1697 return -1;
1698 }
1699 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001700}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001701
Victor Stinnerc5166102012-02-22 13:55:02 +01001702/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001703
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001704 WARNING: The function doesn't copy the terminating null character and
1705 doesn't check the maximum character (may write a latin1 character in an
1706 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001707static void
1708unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1709 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001710{
1711 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1712 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001713 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001714
1715 switch (kind) {
1716 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001717 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001718#ifdef Py_DEBUG
1719 if (PyUnicode_IS_ASCII(unicode)) {
1720 Py_UCS4 maxchar = ucs1lib_find_max_char(
1721 (const Py_UCS1*)str,
1722 (const Py_UCS1*)str + len);
1723 assert(maxchar < 128);
1724 }
1725#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001726 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001727 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001728 }
1729 case PyUnicode_2BYTE_KIND: {
1730 Py_UCS2 *start = (Py_UCS2 *)data + index;
1731 Py_UCS2 *ucs2 = start;
1732 assert(index <= PyUnicode_GET_LENGTH(unicode));
1733
Victor Stinner184252a2012-06-16 02:57:41 +02001734 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001735 *ucs2 = (Py_UCS2)*str;
1736
1737 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001738 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001739 }
1740 default: {
1741 Py_UCS4 *start = (Py_UCS4 *)data + index;
1742 Py_UCS4 *ucs4 = start;
1743 assert(kind == PyUnicode_4BYTE_KIND);
1744 assert(index <= PyUnicode_GET_LENGTH(unicode));
1745
Victor Stinner184252a2012-06-16 02:57:41 +02001746 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001747 *ucs4 = (Py_UCS4)*str;
1748
1749 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 }
1751 }
1752}
1753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754static PyObject*
1755get_latin1_char(unsigned char ch)
1756{
Victor Stinnera464fc12011-10-02 20:39:30 +02001757 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001759 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 if (!unicode)
1761 return NULL;
1762 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001763 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 unicode_latin1[ch] = unicode;
1765 }
1766 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001767 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768}
1769
Victor Stinner985a82a2014-01-03 12:53:47 +01001770static PyObject*
1771unicode_char(Py_UCS4 ch)
1772{
1773 PyObject *unicode;
1774
1775 assert(ch <= MAX_UNICODE);
1776
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001777 if (ch < 256)
1778 return get_latin1_char(ch);
1779
Victor Stinner985a82a2014-01-03 12:53:47 +01001780 unicode = PyUnicode_New(1, ch);
1781 if (unicode == NULL)
1782 return NULL;
1783 switch (PyUnicode_KIND(unicode)) {
1784 case PyUnicode_1BYTE_KIND:
1785 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1786 break;
1787 case PyUnicode_2BYTE_KIND:
1788 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1789 break;
1790 default:
1791 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1792 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1793 }
1794 assert(_PyUnicode_CheckConsistency(unicode, 1));
1795 return unicode;
1796}
1797
Alexander Belopolsky40018472011-02-26 01:02:56 +00001798PyObject *
1799PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001800{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001801 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 Py_UCS4 maxchar = 0;
1803 Py_ssize_t num_surrogates;
1804
1805 if (u == NULL)
1806 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001808 /* If the Unicode data is known at construction time, we can apply
1809 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001812 if (size == 0)
1813 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 /* Single character Unicode objects in the Latin-1 range are
1816 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001817 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return get_latin1_char((unsigned char)*u);
1819
1820 /* If not empty and not single character, copy the Unicode data
1821 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001822 if (find_maxchar_surrogates(u, u + size,
1823 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 return NULL;
1825
Victor Stinner8faf8212011-12-08 22:14:11 +01001826 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001827 if (!unicode)
1828 return NULL;
1829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 switch (PyUnicode_KIND(unicode)) {
1831 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001832 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1834 break;
1835 case PyUnicode_2BYTE_KIND:
1836#if Py_UNICODE_SIZE == 2
1837 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1838#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001839 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1841#endif
1842 break;
1843 case PyUnicode_4BYTE_KIND:
1844#if SIZEOF_WCHAR_T == 2
1845 /* This is the only case which has to process surrogates, thus
1846 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001847 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848#else
1849 assert(num_surrogates == 0);
1850 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1851#endif
1852 break;
1853 default:
1854 assert(0 && "Impossible state");
1855 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001856
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001857 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001858}
1859
Alexander Belopolsky40018472011-02-26 01:02:56 +00001860PyObject *
1861PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001862{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001863 if (size < 0) {
1864 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001865 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 return NULL;
1867 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001868 if (u != NULL)
1869 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1870 else
1871 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001872}
1873
Alexander Belopolsky40018472011-02-26 01:02:56 +00001874PyObject *
1875PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001876{
1877 size_t size = strlen(u);
1878 if (size > PY_SSIZE_T_MAX) {
1879 PyErr_SetString(PyExc_OverflowError, "input too long");
1880 return NULL;
1881 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001882 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001883}
1884
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001885PyObject *
1886_PyUnicode_FromId(_Py_Identifier *id)
1887{
1888 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001889 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1890 strlen(id->string),
1891 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001892 if (!id->object)
1893 return NULL;
1894 PyUnicode_InternInPlace(&id->object);
1895 assert(!id->next);
1896 id->next = static_strings;
1897 static_strings = id;
1898 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001899 return id->object;
1900}
1901
1902void
1903_PyUnicode_ClearStaticStrings()
1904{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001905 _Py_Identifier *tmp, *s = static_strings;
1906 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001907 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 tmp = s->next;
1909 s->next = NULL;
1910 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001911 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001912 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001913}
1914
Benjamin Peterson0df54292012-03-26 14:50:32 -04001915/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916
Victor Stinnerd3f08822012-05-29 12:57:52 +02001917PyObject*
1918_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001919{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001921 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001922 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001923#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001924 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001925#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001926 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001927 }
Victor Stinner785938e2011-12-11 20:09:03 +01001928 unicode = PyUnicode_New(size, 127);
1929 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001930 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001931 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1932 assert(_PyUnicode_CheckConsistency(unicode, 1));
1933 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001934}
1935
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001936static Py_UCS4
1937kind_maxchar_limit(unsigned int kind)
1938{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001939 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001940 case PyUnicode_1BYTE_KIND:
1941 return 0x80;
1942 case PyUnicode_2BYTE_KIND:
1943 return 0x100;
1944 case PyUnicode_4BYTE_KIND:
1945 return 0x10000;
1946 default:
1947 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001948 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001949 }
1950}
1951
Victor Stinnere6abb482012-05-02 01:15:40 +02001952Py_LOCAL_INLINE(Py_UCS4)
1953align_maxchar(Py_UCS4 maxchar)
1954{
1955 if (maxchar <= 127)
1956 return 127;
1957 else if (maxchar <= 255)
1958 return 255;
1959 else if (maxchar <= 65535)
1960 return 65535;
1961 else
1962 return MAX_UNICODE;
1963}
1964
Victor Stinner702c7342011-10-05 13:50:52 +02001965static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001966_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001967{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001969 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001970
Serhiy Storchaka678db842013-01-26 12:16:36 +02001971 if (size == 0)
1972 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001973 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001974 if (size == 1)
1975 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001978 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 if (!res)
1980 return NULL;
1981 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001982 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001983 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001984}
1985
Victor Stinnere57b1c02011-09-28 22:20:48 +02001986static PyObject*
1987_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988{
1989 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001990 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001991
Serhiy Storchaka678db842013-01-26 12:16:36 +02001992 if (size == 0)
1993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001994 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001995 if (size == 1)
1996 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001998 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001999 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 if (!res)
2001 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002004 else {
2005 _PyUnicode_CONVERT_BYTES(
2006 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2007 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002008 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 return res;
2010}
2011
Victor Stinnere57b1c02011-09-28 22:20:48 +02002012static PyObject*
2013_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002014{
2015 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002016 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002017
Serhiy Storchaka678db842013-01-26 12:16:36 +02002018 if (size == 0)
2019 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002020 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002021 if (size == 1)
2022 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002024 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002026 if (!res)
2027 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002028 if (max_char < 256)
2029 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2030 PyUnicode_1BYTE_DATA(res));
2031 else if (max_char < 0x10000)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2033 PyUnicode_2BYTE_DATA(res));
2034 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002035 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002036 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 return res;
2038}
2039
2040PyObject*
2041PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2042{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002043 if (size < 0) {
2044 PyErr_SetString(PyExc_ValueError, "size must be positive");
2045 return NULL;
2046 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002047 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002049 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002051 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002053 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002054 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002055 PyErr_SetString(PyExc_SystemError, "invalid kind");
2056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058}
2059
Victor Stinnerece58de2012-04-23 23:36:38 +02002060Py_UCS4
2061_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2062{
2063 enum PyUnicode_Kind kind;
2064 void *startptr, *endptr;
2065
2066 assert(PyUnicode_IS_READY(unicode));
2067 assert(0 <= start);
2068 assert(end <= PyUnicode_GET_LENGTH(unicode));
2069 assert(start <= end);
2070
2071 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2072 return PyUnicode_MAX_CHAR_VALUE(unicode);
2073
2074 if (start == end)
2075 return 127;
2076
Victor Stinner94d558b2012-04-27 22:26:58 +02002077 if (PyUnicode_IS_ASCII(unicode))
2078 return 127;
2079
Victor Stinnerece58de2012-04-23 23:36:38 +02002080 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002081 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002082 endptr = (char *)startptr + end * kind;
2083 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002084 switch(kind) {
2085 case PyUnicode_1BYTE_KIND:
2086 return ucs1lib_find_max_char(startptr, endptr);
2087 case PyUnicode_2BYTE_KIND:
2088 return ucs2lib_find_max_char(startptr, endptr);
2089 case PyUnicode_4BYTE_KIND:
2090 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002091 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002092 assert(0);
2093 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 }
2095}
2096
Victor Stinner25a4b292011-10-06 12:31:55 +02002097/* Ensure that a string uses the most efficient storage, if it is not the
2098 case: create a new string with of the right kind. Write NULL into *p_unicode
2099 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002100static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002101unicode_adjust_maxchar(PyObject **p_unicode)
2102{
2103 PyObject *unicode, *copy;
2104 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002105 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002106 unsigned int kind;
2107
2108 assert(p_unicode != NULL);
2109 unicode = *p_unicode;
2110 assert(PyUnicode_IS_READY(unicode));
2111 if (PyUnicode_IS_ASCII(unicode))
2112 return;
2113
2114 len = PyUnicode_GET_LENGTH(unicode);
2115 kind = PyUnicode_KIND(unicode);
2116 if (kind == PyUnicode_1BYTE_KIND) {
2117 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002118 max_char = ucs1lib_find_max_char(u, u + len);
2119 if (max_char >= 128)
2120 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002121 }
2122 else if (kind == PyUnicode_2BYTE_KIND) {
2123 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002124 max_char = ucs2lib_find_max_char(u, u + len);
2125 if (max_char >= 256)
2126 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002127 }
2128 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002129 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002131 max_char = ucs4lib_find_max_char(u, u + len);
2132 if (max_char >= 0x10000)
2133 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002134 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002135 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002136 if (copy != NULL)
2137 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 Py_DECREF(unicode);
2139 *p_unicode = copy;
2140}
2141
Victor Stinner034f6cf2011-09-30 02:26:44 +02002142PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002143_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002144{
Victor Stinner87af4f22011-11-21 23:03:47 +01002145 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002146 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002147
Victor Stinner034f6cf2011-09-30 02:26:44 +02002148 if (!PyUnicode_Check(unicode)) {
2149 PyErr_BadInternalCall();
2150 return NULL;
2151 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002152 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002153 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002154
Victor Stinner87af4f22011-11-21 23:03:47 +01002155 length = PyUnicode_GET_LENGTH(unicode);
2156 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157 if (!copy)
2158 return NULL;
2159 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2160
Victor Stinner87af4f22011-11-21 23:03:47 +01002161 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2162 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002163 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002164 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002165}
2166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002167
Victor Stinnerbc603d12011-10-02 01:00:40 +02002168/* Widen Unicode objects to larger buffers. Don't write terminating null
2169 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
2171void*
2172_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2173{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002174 Py_ssize_t len;
2175 void *result;
2176 unsigned int skind;
2177
Benjamin Petersonbac79492012-01-14 13:34:47 -05002178 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002179 return NULL;
2180
2181 len = PyUnicode_GET_LENGTH(s);
2182 skind = PyUnicode_KIND(s);
2183 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002184 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 return NULL;
2186 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002188 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002189 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002190 if (!result)
2191 return PyErr_NoMemory();
2192 assert(skind == PyUnicode_1BYTE_KIND);
2193 _PyUnicode_CONVERT_BYTES(
2194 Py_UCS1, Py_UCS2,
2195 PyUnicode_1BYTE_DATA(s),
2196 PyUnicode_1BYTE_DATA(s) + len,
2197 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002199 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002200 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002201 if (!result)
2202 return PyErr_NoMemory();
2203 if (skind == PyUnicode_2BYTE_KIND) {
2204 _PyUnicode_CONVERT_BYTES(
2205 Py_UCS2, Py_UCS4,
2206 PyUnicode_2BYTE_DATA(s),
2207 PyUnicode_2BYTE_DATA(s) + len,
2208 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002210 else {
2211 assert(skind == PyUnicode_1BYTE_KIND);
2212 _PyUnicode_CONVERT_BYTES(
2213 Py_UCS1, Py_UCS4,
2214 PyUnicode_1BYTE_DATA(s),
2215 PyUnicode_1BYTE_DATA(s) + len,
2216 result);
2217 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002219 default:
2220 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 }
Victor Stinner01698042011-10-04 00:04:26 +02002222 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223 return NULL;
2224}
2225
2226static Py_UCS4*
2227as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2228 int copy_null)
2229{
2230 int kind;
2231 void *data;
2232 Py_ssize_t len, targetlen;
2233 if (PyUnicode_READY(string) == -1)
2234 return NULL;
2235 kind = PyUnicode_KIND(string);
2236 data = PyUnicode_DATA(string);
2237 len = PyUnicode_GET_LENGTH(string);
2238 targetlen = len;
2239 if (copy_null)
2240 targetlen++;
2241 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002242 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002243 if (!target) {
2244 PyErr_NoMemory();
2245 return NULL;
2246 }
2247 }
2248 else {
2249 if (targetsize < targetlen) {
2250 PyErr_Format(PyExc_SystemError,
2251 "string is longer than the buffer");
2252 if (copy_null && 0 < targetsize)
2253 target[0] = 0;
2254 return NULL;
2255 }
2256 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002257 if (kind == PyUnicode_1BYTE_KIND) {
2258 Py_UCS1 *start = (Py_UCS1 *) data;
2259 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002261 else if (kind == PyUnicode_2BYTE_KIND) {
2262 Py_UCS2 *start = (Py_UCS2 *) data;
2263 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2264 }
2265 else {
2266 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002269 if (copy_null)
2270 target[len] = 0;
2271 return target;
2272}
2273
2274Py_UCS4*
2275PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2276 int copy_null)
2277{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002278 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002279 PyErr_BadInternalCall();
2280 return NULL;
2281 }
2282 return as_ucs4(string, target, targetsize, copy_null);
2283}
2284
2285Py_UCS4*
2286PyUnicode_AsUCS4Copy(PyObject *string)
2287{
2288 return as_ucs4(string, NULL, 0, 1);
2289}
2290
2291#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002292
Alexander Belopolsky40018472011-02-26 01:02:56 +00002293PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002294PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002295{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002296 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002297 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002298 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002299 PyErr_BadInternalCall();
2300 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002301 }
2302
Martin v. Löwis790465f2008-04-05 20:41:37 +00002303 if (size == -1) {
2304 size = wcslen(w);
2305 }
2306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002308}
2309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002311
Victor Stinner15a11362012-10-06 23:48:20 +02002312/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002313 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2314 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2315#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002316
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002317static int
2318unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2319 Py_ssize_t width, Py_ssize_t precision)
2320{
2321 Py_ssize_t length, fill, arglen;
2322 Py_UCS4 maxchar;
2323
2324 if (PyUnicode_READY(str) == -1)
2325 return -1;
2326
2327 length = PyUnicode_GET_LENGTH(str);
2328 if ((precision == -1 || precision >= length)
2329 && width <= length)
2330 return _PyUnicodeWriter_WriteStr(writer, str);
2331
2332 if (precision != -1)
2333 length = Py_MIN(precision, length);
2334
2335 arglen = Py_MAX(length, width);
2336 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2337 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2338 else
2339 maxchar = writer->maxchar;
2340
2341 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2342 return -1;
2343
2344 if (width > length) {
2345 fill = width - length;
2346 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2347 return -1;
2348 writer->pos += fill;
2349 }
2350
2351 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2352 str, 0, length);
2353 writer->pos += length;
2354 return 0;
2355}
2356
2357static int
2358unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2359 Py_ssize_t width, Py_ssize_t precision)
2360{
2361 /* UTF-8 */
2362 Py_ssize_t length;
2363 PyObject *unicode;
2364 int res;
2365
2366 length = strlen(str);
2367 if (precision != -1)
2368 length = Py_MIN(length, precision);
2369 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2370 if (unicode == NULL)
2371 return -1;
2372
2373 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2374 Py_DECREF(unicode);
2375 return res;
2376}
2377
Victor Stinner96865452011-03-01 23:44:09 +00002378static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002379unicode_fromformat_arg(_PyUnicodeWriter *writer,
2380 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002381{
Victor Stinnere215d962012-10-06 23:03:36 +02002382 const char *p;
2383 Py_ssize_t len;
2384 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002385 Py_ssize_t width;
2386 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002387 int longflag;
2388 int longlongflag;
2389 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002390 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002391
2392 p = f;
2393 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002394 zeropad = 0;
2395 if (*f == '0') {
2396 zeropad = 1;
2397 f++;
2398 }
Victor Stinner96865452011-03-01 23:44:09 +00002399
2400 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002401 width = -1;
2402 if (Py_ISDIGIT((unsigned)*f)) {
2403 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002404 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002405 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002406 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002407 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002408 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002409 return NULL;
2410 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002411 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002412 f++;
2413 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002414 }
2415 precision = -1;
2416 if (*f == '.') {
2417 f++;
2418 if (Py_ISDIGIT((unsigned)*f)) {
2419 precision = (*f - '0');
2420 f++;
2421 while (Py_ISDIGIT((unsigned)*f)) {
2422 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2423 PyErr_SetString(PyExc_ValueError,
2424 "precision too big");
2425 return NULL;
2426 }
2427 precision = (precision * 10) + (*f - '0');
2428 f++;
2429 }
2430 }
Victor Stinner96865452011-03-01 23:44:09 +00002431 if (*f == '%') {
2432 /* "%.3%s" => f points to "3" */
2433 f--;
2434 }
2435 }
2436 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002437 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002438 f--;
2439 }
Victor Stinner96865452011-03-01 23:44:09 +00002440
2441 /* Handle %ld, %lu, %lld and %llu. */
2442 longflag = 0;
2443 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002444 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002445 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002446 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002447 longflag = 1;
2448 ++f;
2449 }
2450#ifdef HAVE_LONG_LONG
2451 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002452 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002453 longlongflag = 1;
2454 f += 2;
2455 }
2456#endif
2457 }
2458 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002459 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002460 size_tflag = 1;
2461 ++f;
2462 }
Victor Stinnere215d962012-10-06 23:03:36 +02002463
2464 if (f[1] == '\0')
2465 writer->overallocate = 0;
2466
2467 switch (*f) {
2468 case 'c':
2469 {
2470 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002471 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002472 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002473 "character argument not in range(0x110000)");
2474 return NULL;
2475 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002476 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002477 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002478 break;
2479 }
2480
2481 case 'i':
2482 case 'd':
2483 case 'u':
2484 case 'x':
2485 {
2486 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002487 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002488 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002489
2490 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002491 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002492 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002493 va_arg(*vargs, unsigned long));
2494#ifdef HAVE_LONG_LONG
2495 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002496 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002497 va_arg(*vargs, unsigned PY_LONG_LONG));
2498#endif
2499 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002500 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002501 va_arg(*vargs, size_t));
2502 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002503 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002504 va_arg(*vargs, unsigned int));
2505 }
2506 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002507 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002508 }
2509 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002510 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002511 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002512 va_arg(*vargs, long));
2513#ifdef HAVE_LONG_LONG
2514 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002515 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002516 va_arg(*vargs, PY_LONG_LONG));
2517#endif
2518 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002519 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002520 va_arg(*vargs, Py_ssize_t));
2521 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002522 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002523 va_arg(*vargs, int));
2524 }
2525 assert(len >= 0);
2526
Victor Stinnere215d962012-10-06 23:03:36 +02002527 if (precision < len)
2528 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002529
2530 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002531 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2532 return NULL;
2533
Victor Stinnere215d962012-10-06 23:03:36 +02002534 if (width > precision) {
2535 Py_UCS4 fillchar;
2536 fill = width - precision;
2537 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002538 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2539 return NULL;
2540 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002541 }
Victor Stinner15a11362012-10-06 23:48:20 +02002542 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002543 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002544 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2545 return NULL;
2546 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002547 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002548
Victor Stinner4a587072013-11-19 12:54:53 +01002549 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2550 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002551 break;
2552 }
2553
2554 case 'p':
2555 {
2556 char number[MAX_LONG_LONG_CHARS];
2557
2558 len = sprintf(number, "%p", va_arg(*vargs, void*));
2559 assert(len >= 0);
2560
2561 /* %p is ill-defined: ensure leading 0x. */
2562 if (number[1] == 'X')
2563 number[1] = 'x';
2564 else if (number[1] != 'x') {
2565 memmove(number + 2, number,
2566 strlen(number) + 1);
2567 number[0] = '0';
2568 number[1] = 'x';
2569 len += 2;
2570 }
2571
Victor Stinner4a587072013-11-19 12:54:53 +01002572 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002573 return NULL;
2574 break;
2575 }
2576
2577 case 's':
2578 {
2579 /* UTF-8 */
2580 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002582 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002583 break;
2584 }
2585
2586 case 'U':
2587 {
2588 PyObject *obj = va_arg(*vargs, PyObject *);
2589 assert(obj && _PyUnicode_CHECK(obj));
2590
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002591 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002592 return NULL;
2593 break;
2594 }
2595
2596 case 'V':
2597 {
2598 PyObject *obj = va_arg(*vargs, PyObject *);
2599 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002600 if (obj) {
2601 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002603 return NULL;
2604 }
2605 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002606 assert(str != NULL);
2607 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002608 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002609 }
2610 break;
2611 }
2612
2613 case 'S':
2614 {
2615 PyObject *obj = va_arg(*vargs, PyObject *);
2616 PyObject *str;
2617 assert(obj);
2618 str = PyObject_Str(obj);
2619 if (!str)
2620 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002621 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002622 Py_DECREF(str);
2623 return NULL;
2624 }
2625 Py_DECREF(str);
2626 break;
2627 }
2628
2629 case 'R':
2630 {
2631 PyObject *obj = va_arg(*vargs, PyObject *);
2632 PyObject *repr;
2633 assert(obj);
2634 repr = PyObject_Repr(obj);
2635 if (!repr)
2636 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002637 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002638 Py_DECREF(repr);
2639 return NULL;
2640 }
2641 Py_DECREF(repr);
2642 break;
2643 }
2644
2645 case 'A':
2646 {
2647 PyObject *obj = va_arg(*vargs, PyObject *);
2648 PyObject *ascii;
2649 assert(obj);
2650 ascii = PyObject_ASCII(obj);
2651 if (!ascii)
2652 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002653 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002654 Py_DECREF(ascii);
2655 return NULL;
2656 }
2657 Py_DECREF(ascii);
2658 break;
2659 }
2660
2661 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002662 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002663 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002664 break;
2665
2666 default:
2667 /* if we stumble upon an unknown formatting code, copy the rest
2668 of the format string to the output string. (we cannot just
2669 skip the code, since there's no way to know what's in the
2670 argument list) */
2671 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002672 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002673 return NULL;
2674 f = p+len;
2675 return f;
2676 }
2677
2678 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002679 return f;
2680}
2681
Walter Dörwaldd2034312007-05-18 16:29:38 +00002682PyObject *
2683PyUnicode_FromFormatV(const char *format, va_list vargs)
2684{
Victor Stinnere215d962012-10-06 23:03:36 +02002685 va_list vargs2;
2686 const char *f;
2687 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002688
Victor Stinner8f674cc2013-04-17 23:02:17 +02002689 _PyUnicodeWriter_Init(&writer);
2690 writer.min_length = strlen(format) + 100;
2691 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002692
2693 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2694 Copy it to be able to pass a reference to a subfunction. */
2695 Py_VA_COPY(vargs2, vargs);
2696
2697 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002699 f = unicode_fromformat_arg(&writer, f, &vargs2);
2700 if (f == NULL)
2701 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002702 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002704 const char *p;
2705 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002706
Victor Stinnere215d962012-10-06 23:03:36 +02002707 p = f;
2708 do
2709 {
2710 if ((unsigned char)*p > 127) {
2711 PyErr_Format(PyExc_ValueError,
2712 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2713 "string, got a non-ASCII byte: 0x%02x",
2714 (unsigned char)*p);
2715 return NULL;
2716 }
2717 p++;
2718 }
2719 while (*p != '\0' && *p != '%');
2720 len = p - f;
2721
2722 if (*p == '\0')
2723 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002724
2725 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002726 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002727
2728 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002729 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002730 }
Victor Stinnere215d962012-10-06 23:03:36 +02002731 return _PyUnicodeWriter_Finish(&writer);
2732
2733 fail:
2734 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002736}
2737
Walter Dörwaldd2034312007-05-18 16:29:38 +00002738PyObject *
2739PyUnicode_FromFormat(const char *format, ...)
2740{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 PyObject* ret;
2742 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002743
2744#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002746#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002747 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002748#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 ret = PyUnicode_FromFormatV(format, vargs);
2750 va_end(vargs);
2751 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752}
2753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002754#ifdef HAVE_WCHAR_H
2755
Victor Stinner5593d8a2010-10-02 11:11:27 +00002756/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2757 convert a Unicode object to a wide character string.
2758
Victor Stinnerd88d9832011-09-06 02:00:05 +02002759 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002760 character) required to convert the unicode object. Ignore size argument.
2761
Victor Stinnerd88d9832011-09-06 02:00:05 +02002762 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002763 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002764 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002765static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002766unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002767 wchar_t *w,
2768 Py_ssize_t size)
2769{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002770 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 const wchar_t *wstr;
2772
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002773 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 if (wstr == NULL)
2775 return -1;
2776
Victor Stinner5593d8a2010-10-02 11:11:27 +00002777 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002778 if (size > res)
2779 size = res + 1;
2780 else
2781 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002782 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002783 return res;
2784 }
2785 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002786 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002787}
2788
2789Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002790PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002791 wchar_t *w,
2792 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002793{
2794 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002795 PyErr_BadInternalCall();
2796 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002797 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002798 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002799}
2800
Victor Stinner137c34c2010-09-29 10:25:54 +00002801wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002802PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002803 Py_ssize_t *size)
2804{
2805 wchar_t* buffer;
2806 Py_ssize_t buflen;
2807
2808 if (unicode == NULL) {
2809 PyErr_BadInternalCall();
2810 return NULL;
2811 }
2812
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002813 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002814 if (buflen == -1)
2815 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002816 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002817 if (buffer == NULL) {
2818 PyErr_NoMemory();
2819 return NULL;
2820 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002821 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002822 if (buflen == -1) {
2823 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002824 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002825 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002826 if (size != NULL)
2827 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002828 return buffer;
2829}
2830
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002831#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002832
Alexander Belopolsky40018472011-02-26 01:02:56 +00002833PyObject *
2834PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002835{
Victor Stinner8faf8212011-12-08 22:14:11 +01002836 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002837 PyErr_SetString(PyExc_ValueError,
2838 "chr() arg not in range(0x110000)");
2839 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002840 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002841
Victor Stinner985a82a2014-01-03 12:53:47 +01002842 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002843}
2844
Alexander Belopolsky40018472011-02-26 01:02:56 +00002845PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002846PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002847{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002848 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002849 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002850 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002851 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002852 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002853 Py_INCREF(obj);
2854 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002855 }
2856 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 /* For a Unicode subtype that's not a Unicode object,
2858 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002859 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002860 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002861 PyErr_Format(PyExc_TypeError,
2862 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002863 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002864 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002865}
2866
Alexander Belopolsky40018472011-02-26 01:02:56 +00002867PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002868PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002869 const char *encoding,
2870 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002871{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002872 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002873 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002874
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002876 PyErr_BadInternalCall();
2877 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002878 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002879
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002880 /* Decoding bytes objects is the most common case and should be fast */
2881 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002882 if (PyBytes_GET_SIZE(obj) == 0)
2883 _Py_RETURN_UNICODE_EMPTY();
2884 v = PyUnicode_Decode(
2885 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2886 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002887 return v;
2888 }
2889
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002890 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002891 PyErr_SetString(PyExc_TypeError,
2892 "decoding str is not supported");
2893 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002894 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002895
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002896 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2897 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2898 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002899 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002900 Py_TYPE(obj)->tp_name);
2901 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002902 }
Tim Petersced69f82003-09-16 20:30:58 +00002903
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002904 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002905 PyBuffer_Release(&buffer);
2906 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002908
Serhiy Storchaka05997252013-01-26 12:14:02 +02002909 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002910 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002911 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912}
2913
Victor Stinner600d3be2010-06-10 12:00:55 +00002914/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002915 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2916 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002917int
2918_Py_normalize_encoding(const char *encoding,
2919 char *lower,
2920 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002922 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002923 char *l;
2924 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002925
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002926 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002927 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002928 if (lower_len < 6)
2929 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002930 strcpy(lower, "utf-8");
2931 return 1;
2932 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002933 e = encoding;
2934 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002935 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002936 while (*e) {
2937 if (l == l_end)
2938 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002939 if (Py_ISUPPER(*e)) {
2940 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002941 }
2942 else if (*e == '_') {
2943 *l++ = '-';
2944 e++;
2945 }
2946 else {
2947 *l++ = *e++;
2948 }
2949 }
2950 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002951 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002952}
2953
Alexander Belopolsky40018472011-02-26 01:02:56 +00002954PyObject *
2955PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002956 Py_ssize_t size,
2957 const char *encoding,
2958 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002959{
2960 PyObject *buffer = NULL, *unicode;
2961 Py_buffer info;
2962 char lower[11]; /* Enough for any encoding shortcut */
2963
Fred Drakee4315f52000-05-09 19:53:39 +00002964 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002965 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002966 if ((strcmp(lower, "utf-8") == 0) ||
2967 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002968 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002969 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002970 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002971 (strcmp(lower, "iso-8859-1") == 0) ||
2972 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002973 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002974#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002975 else if (strcmp(lower, "mbcs") == 0)
2976 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002977#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002978 else if (strcmp(lower, "ascii") == 0)
2979 return PyUnicode_DecodeASCII(s, size, errors);
2980 else if (strcmp(lower, "utf-16") == 0)
2981 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2982 else if (strcmp(lower, "utf-32") == 0)
2983 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002985
2986 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002987 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002988 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002989 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002990 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002991 if (buffer == NULL)
2992 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10002993 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002994 if (unicode == NULL)
2995 goto onError;
2996 if (!PyUnicode_Check(unicode)) {
2997 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10002998 "'%.400s' decoder returned '%.400s' instead of 'str'; "
2999 "use codecs.decode() to decode to arbitrary types",
3000 encoding,
3001 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003002 Py_DECREF(unicode);
3003 goto onError;
3004 }
3005 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003006 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003007
Benjamin Peterson29060642009-01-31 22:14:21 +00003008 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003009 Py_XDECREF(buffer);
3010 return NULL;
3011}
3012
Alexander Belopolsky40018472011-02-26 01:02:56 +00003013PyObject *
3014PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003015 const char *encoding,
3016 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003017{
3018 PyObject *v;
3019
3020 if (!PyUnicode_Check(unicode)) {
3021 PyErr_BadArgument();
3022 goto onError;
3023 }
3024
3025 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003026 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003027
3028 /* Decode via the codec registry */
3029 v = PyCodec_Decode(unicode, encoding, errors);
3030 if (v == NULL)
3031 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003032 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003033
Benjamin Peterson29060642009-01-31 22:14:21 +00003034 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003035 return NULL;
3036}
3037
Alexander Belopolsky40018472011-02-26 01:02:56 +00003038PyObject *
3039PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003040 const char *encoding,
3041 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003042{
3043 PyObject *v;
3044
3045 if (!PyUnicode_Check(unicode)) {
3046 PyErr_BadArgument();
3047 goto onError;
3048 }
3049
3050 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003051 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003052
3053 /* Decode via the codec registry */
3054 v = PyCodec_Decode(unicode, encoding, errors);
3055 if (v == NULL)
3056 goto onError;
3057 if (!PyUnicode_Check(v)) {
3058 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003059 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3060 "use codecs.decode() to decode to arbitrary types",
3061 encoding,
3062 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003063 Py_DECREF(v);
3064 goto onError;
3065 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003066 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003067
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003069 return NULL;
3070}
3071
Alexander Belopolsky40018472011-02-26 01:02:56 +00003072PyObject *
3073PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003074 Py_ssize_t size,
3075 const char *encoding,
3076 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003077{
3078 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003079
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080 unicode = PyUnicode_FromUnicode(s, size);
3081 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003082 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003083 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3084 Py_DECREF(unicode);
3085 return v;
3086}
3087
Alexander Belopolsky40018472011-02-26 01:02:56 +00003088PyObject *
3089PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003090 const char *encoding,
3091 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003092{
3093 PyObject *v;
3094
3095 if (!PyUnicode_Check(unicode)) {
3096 PyErr_BadArgument();
3097 goto onError;
3098 }
3099
3100 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003101 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003102
3103 /* Encode via the codec registry */
3104 v = PyCodec_Encode(unicode, encoding, errors);
3105 if (v == NULL)
3106 goto onError;
3107 return v;
3108
Benjamin Peterson29060642009-01-31 22:14:21 +00003109 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003110 return NULL;
3111}
3112
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003113static size_t
3114wcstombs_errorpos(const wchar_t *wstr)
3115{
3116 size_t len;
3117#if SIZEOF_WCHAR_T == 2
3118 wchar_t buf[3];
3119#else
3120 wchar_t buf[2];
3121#endif
3122 char outbuf[MB_LEN_MAX];
3123 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003124
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003125#if SIZEOF_WCHAR_T == 2
3126 buf[2] = 0;
3127#else
3128 buf[1] = 0;
3129#endif
3130 start = wstr;
3131 while (*wstr != L'\0')
3132 {
3133 previous = wstr;
3134#if SIZEOF_WCHAR_T == 2
3135 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3136 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3137 {
3138 buf[0] = wstr[0];
3139 buf[1] = wstr[1];
3140 wstr += 2;
3141 }
3142 else {
3143 buf[0] = *wstr;
3144 buf[1] = 0;
3145 wstr++;
3146 }
3147#else
3148 buf[0] = *wstr;
3149 wstr++;
3150#endif
3151 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003152 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003153 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154 }
3155
3156 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157 return 0;
3158}
3159
Victor Stinner1b579672011-12-17 05:47:23 +01003160static int
3161locale_error_handler(const char *errors, int *surrogateescape)
3162{
3163 if (errors == NULL) {
3164 *surrogateescape = 0;
3165 return 0;
3166 }
3167
3168 if (strcmp(errors, "strict") == 0) {
3169 *surrogateescape = 0;
3170 return 0;
3171 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003172 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003173 *surrogateescape = 1;
3174 return 0;
3175 }
3176 PyErr_Format(PyExc_ValueError,
3177 "only 'strict' and 'surrogateescape' error handlers "
3178 "are supported, not '%s'",
3179 errors);
3180 return -1;
3181}
3182
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003184PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003185{
3186 Py_ssize_t wlen, wlen2;
3187 wchar_t *wstr;
3188 PyObject *bytes = NULL;
3189 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003190 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003191 PyObject *exc;
3192 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003193 int surrogateescape;
3194
3195 if (locale_error_handler(errors, &surrogateescape) < 0)
3196 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003197
3198 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3199 if (wstr == NULL)
3200 return NULL;
3201
3202 wlen2 = wcslen(wstr);
3203 if (wlen2 != wlen) {
3204 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003205 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003206 return NULL;
3207 }
3208
3209 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003210 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211 char *str;
3212
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003213 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214 if (str == NULL) {
3215 if (error_pos == (size_t)-1) {
3216 PyErr_NoMemory();
3217 PyMem_Free(wstr);
3218 return NULL;
3219 }
3220 else {
3221 goto encode_error;
3222 }
3223 }
3224 PyMem_Free(wstr);
3225
3226 bytes = PyBytes_FromString(str);
3227 PyMem_Free(str);
3228 }
3229 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003230 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003231 size_t len, len2;
3232
3233 len = wcstombs(NULL, wstr, 0);
3234 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003235 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003236 goto encode_error;
3237 }
3238
3239 bytes = PyBytes_FromStringAndSize(NULL, len);
3240 if (bytes == NULL) {
3241 PyMem_Free(wstr);
3242 return NULL;
3243 }
3244
3245 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3246 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003247 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003248 goto encode_error;
3249 }
3250 PyMem_Free(wstr);
3251 }
3252 return bytes;
3253
3254encode_error:
3255 errmsg = strerror(errno);
3256 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003257
3258 if (error_pos == (size_t)-1)
3259 error_pos = wcstombs_errorpos(wstr);
3260
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261 PyMem_Free(wstr);
3262 Py_XDECREF(bytes);
3263
Victor Stinner2f197072011-12-17 07:08:30 +01003264 if (errmsg != NULL) {
3265 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003266 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003267 if (wstr != NULL) {
3268 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003269 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003270 } else
3271 errmsg = NULL;
3272 }
3273 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003274 reason = PyUnicode_FromString(
3275 "wcstombs() encountered an unencodable "
3276 "wide character");
3277 if (reason == NULL)
3278 return NULL;
3279
3280 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3281 "locale", unicode,
3282 (Py_ssize_t)error_pos,
3283 (Py_ssize_t)(error_pos+1),
3284 reason);
3285 Py_DECREF(reason);
3286 if (exc != NULL) {
3287 PyCodec_StrictErrors(exc);
3288 Py_XDECREF(exc);
3289 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 return NULL;
3291}
3292
Victor Stinnerad158722010-10-27 00:25:46 +00003293PyObject *
3294PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003295{
Victor Stinner99b95382011-07-04 14:23:54 +02003296#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003297 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003298#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003299 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003300#else
Victor Stinner793b5312011-04-27 00:24:21 +02003301 PyInterpreterState *interp = PyThreadState_GET()->interp;
3302 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3303 cannot use it to encode and decode filenames before it is loaded. Load
3304 the Python codec requires to encode at least its own filename. Use the C
3305 version of the locale codec until the codec registry is initialized and
3306 the Python codec is loaded.
3307
3308 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3309 cannot only rely on it: check also interp->fscodec_initialized for
3310 subinterpreters. */
3311 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003312 return PyUnicode_AsEncodedString(unicode,
3313 Py_FileSystemDefaultEncoding,
3314 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003315 }
3316 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003317 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003318 }
Victor Stinnerad158722010-10-27 00:25:46 +00003319#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320}
3321
Alexander Belopolsky40018472011-02-26 01:02:56 +00003322PyObject *
3323PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003324 const char *encoding,
3325 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003326{
3327 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003328 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003329
Guido van Rossumd57fd912000-03-10 22:53:23 +00003330 if (!PyUnicode_Check(unicode)) {
3331 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003332 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333 }
Fred Drakee4315f52000-05-09 19:53:39 +00003334
Fred Drakee4315f52000-05-09 19:53:39 +00003335 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003336 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003337 if ((strcmp(lower, "utf-8") == 0) ||
3338 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003339 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003340 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003342 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003343 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003344 }
Victor Stinner37296e82010-06-10 13:36:23 +00003345 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003346 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003347 (strcmp(lower, "iso-8859-1") == 0) ||
3348 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003349 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003350#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003351 else if (strcmp(lower, "mbcs") == 0)
3352 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003353#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003354 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003356 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003357
3358 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003359 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003360 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 return NULL;
3362
3363 /* The normal path */
3364 if (PyBytes_Check(v))
3365 return v;
3366
3367 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003368 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003369 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003370 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003371
3372 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003373 "encoder %s returned bytearray instead of bytes; "
3374 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003375 encoding);
3376 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003377 Py_DECREF(v);
3378 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003379 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003380
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003381 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3382 Py_DECREF(v);
3383 return b;
3384 }
3385
3386 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003387 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3388 "use codecs.encode() to encode to arbitrary types",
3389 encoding,
3390 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003391 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392 return NULL;
3393}
3394
Alexander Belopolsky40018472011-02-26 01:02:56 +00003395PyObject *
3396PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003397 const char *encoding,
3398 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003399{
3400 PyObject *v;
3401
3402 if (!PyUnicode_Check(unicode)) {
3403 PyErr_BadArgument();
3404 goto onError;
3405 }
3406
3407 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003408 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003409
3410 /* Encode via the codec registry */
3411 v = PyCodec_Encode(unicode, encoding, errors);
3412 if (v == NULL)
3413 goto onError;
3414 if (!PyUnicode_Check(v)) {
3415 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003416 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3417 "use codecs.encode() to encode to arbitrary types",
3418 encoding,
3419 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003420 Py_DECREF(v);
3421 goto onError;
3422 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003423 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003424
Benjamin Peterson29060642009-01-31 22:14:21 +00003425 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003426 return NULL;
3427}
3428
Victor Stinner2f197072011-12-17 07:08:30 +01003429static size_t
3430mbstowcs_errorpos(const char *str, size_t len)
3431{
3432#ifdef HAVE_MBRTOWC
3433 const char *start = str;
3434 mbstate_t mbs;
3435 size_t converted;
3436 wchar_t ch;
3437
3438 memset(&mbs, 0, sizeof mbs);
3439 while (len)
3440 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003441 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003442 if (converted == 0)
3443 /* Reached end of string */
3444 break;
3445 if (converted == (size_t)-1 || converted == (size_t)-2) {
3446 /* Conversion error or incomplete character */
3447 return str - start;
3448 }
3449 else {
3450 str += converted;
3451 len -= converted;
3452 }
3453 }
3454 /* failed to find the undecodable byte sequence */
3455 return 0;
3456#endif
3457 return 0;
3458}
3459
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003460PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003461PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003462 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003463{
3464 wchar_t smallbuf[256];
3465 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3466 wchar_t *wstr;
3467 size_t wlen, wlen2;
3468 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003469 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003470 size_t error_pos;
3471 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003472 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3473 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003474
3475 if (locale_error_handler(errors, &surrogateescape) < 0)
3476 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003477
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003478 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3479 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480 return NULL;
3481 }
3482
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003483 if (surrogateescape) {
3484 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003485 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003486 if (wstr == NULL) {
3487 if (wlen == (size_t)-1)
3488 PyErr_NoMemory();
3489 else
3490 PyErr_SetFromErrno(PyExc_OSError);
3491 return NULL;
3492 }
3493
3494 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003495 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003496 }
3497 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003498 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499#ifndef HAVE_BROKEN_MBSTOWCS
3500 wlen = mbstowcs(NULL, str, 0);
3501#else
3502 wlen = len;
3503#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003504 if (wlen == (size_t)-1)
3505 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003506 if (wlen+1 <= smallbuf_len) {
3507 wstr = smallbuf;
3508 }
3509 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003510 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003511 if (!wstr)
3512 return PyErr_NoMemory();
3513 }
3514
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003515 wlen2 = mbstowcs(wstr, str, wlen+1);
3516 if (wlen2 == (size_t)-1) {
3517 if (wstr != smallbuf)
3518 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003519 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003520 }
3521#ifdef HAVE_BROKEN_MBSTOWCS
3522 assert(wlen2 == wlen);
3523#endif
3524 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3525 if (wstr != smallbuf)
3526 PyMem_Free(wstr);
3527 }
3528 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003529
3530decode_error:
3531 errmsg = strerror(errno);
3532 assert(errmsg != NULL);
3533
3534 error_pos = mbstowcs_errorpos(str, len);
3535 if (errmsg != NULL) {
3536 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003537 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003538 if (wstr != NULL) {
3539 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003540 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003541 } else
3542 errmsg = NULL;
3543 }
3544 if (errmsg == NULL)
3545 reason = PyUnicode_FromString(
3546 "mbstowcs() encountered an invalid multibyte sequence");
3547 if (reason == NULL)
3548 return NULL;
3549
3550 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3551 "locale", str, len,
3552 (Py_ssize_t)error_pos,
3553 (Py_ssize_t)(error_pos+1),
3554 reason);
3555 Py_DECREF(reason);
3556 if (exc != NULL) {
3557 PyCodec_StrictErrors(exc);
3558 Py_XDECREF(exc);
3559 }
3560 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003561}
3562
3563PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003564PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003565{
3566 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003567 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003568}
3569
3570
3571PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003572PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003573 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003574 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3575}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576
Christian Heimes5894ba72007-11-04 11:43:14 +00003577PyObject*
3578PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3579{
Victor Stinner99b95382011-07-04 14:23:54 +02003580#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003581 return PyUnicode_DecodeMBCS(s, size, NULL);
3582#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003583 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003584#else
Victor Stinner793b5312011-04-27 00:24:21 +02003585 PyInterpreterState *interp = PyThreadState_GET()->interp;
3586 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3587 cannot use it to encode and decode filenames before it is loaded. Load
3588 the Python codec requires to encode at least its own filename. Use the C
3589 version of the locale codec until the codec registry is initialized and
3590 the Python codec is loaded.
3591
3592 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3593 cannot only rely on it: check also interp->fscodec_initialized for
3594 subinterpreters. */
3595 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003596 return PyUnicode_Decode(s, size,
3597 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003598 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003599 }
3600 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003601 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003602 }
Victor Stinnerad158722010-10-27 00:25:46 +00003603#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003604}
3605
Martin v. Löwis011e8422009-05-05 04:43:17 +00003606
3607int
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003608_PyUnicode_HasNULChars(PyObject* str)
Antoine Pitrou13348842012-01-29 18:36:34 +01003609{
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003610 Py_ssize_t pos;
Antoine Pitrou13348842012-01-29 18:36:34 +01003611
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003612 if (PyUnicode_READY(str) == -1)
Antoine Pitrou13348842012-01-29 18:36:34 +01003613 return -1;
Victor Stinnerfe75fb42012-10-23 02:52:18 +02003614 pos = findchar(PyUnicode_DATA(str), PyUnicode_KIND(str),
3615 PyUnicode_GET_LENGTH(str), '\0', 1);
3616 if (pos == -1)
3617 return 0;
3618 else
3619 return 1;
Antoine Pitrou13348842012-01-29 18:36:34 +01003620}
3621
Antoine Pitrou13348842012-01-29 18:36:34 +01003622int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003623PyUnicode_FSConverter(PyObject* arg, void* addr)
3624{
3625 PyObject *output = NULL;
3626 Py_ssize_t size;
3627 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003628 if (arg == NULL) {
3629 Py_DECREF(*(PyObject**)addr);
3630 return 1;
3631 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003632 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003633 output = arg;
3634 Py_INCREF(output);
3635 }
3636 else {
3637 arg = PyUnicode_FromObject(arg);
3638 if (!arg)
3639 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003640 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003641 Py_DECREF(arg);
3642 if (!output)
3643 return 0;
3644 if (!PyBytes_Check(output)) {
3645 Py_DECREF(output);
3646 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3647 return 0;
3648 }
3649 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003650 size = PyBytes_GET_SIZE(output);
3651 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003652 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003653 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003654 Py_DECREF(output);
3655 return 0;
3656 }
3657 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003658 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003659}
3660
3661
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003662int
3663PyUnicode_FSDecoder(PyObject* arg, void* addr)
3664{
3665 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003666 if (arg == NULL) {
3667 Py_DECREF(*(PyObject**)addr);
3668 return 1;
3669 }
3670 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003671 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003672 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003673 output = arg;
3674 Py_INCREF(output);
3675 }
3676 else {
3677 arg = PyBytes_FromObject(arg);
3678 if (!arg)
3679 return 0;
3680 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3681 PyBytes_GET_SIZE(arg));
3682 Py_DECREF(arg);
3683 if (!output)
3684 return 0;
3685 if (!PyUnicode_Check(output)) {
3686 Py_DECREF(output);
3687 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3688 return 0;
3689 }
3690 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003691 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003692 Py_DECREF(output);
3693 return 0;
3694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003696 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003697 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003698 Py_DECREF(output);
3699 return 0;
3700 }
3701 *(PyObject**)addr = output;
3702 return Py_CLEANUP_SUPPORTED;
3703}
3704
3705
Martin v. Löwis5b222132007-06-10 09:51:05 +00003706char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003707PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003708{
Christian Heimesf3863112007-11-22 07:46:41 +00003709 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003710
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003711 if (!PyUnicode_Check(unicode)) {
3712 PyErr_BadArgument();
3713 return NULL;
3714 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003715 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003716 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003717
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003718 if (PyUnicode_UTF8(unicode) == NULL) {
3719 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003720 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3721 if (bytes == NULL)
3722 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003723 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3724 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003725 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726 Py_DECREF(bytes);
3727 return NULL;
3728 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003729 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3730 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3731 PyBytes_AS_STRING(bytes),
3732 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003733 Py_DECREF(bytes);
3734 }
3735
3736 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003737 *psize = PyUnicode_UTF8_LENGTH(unicode);
3738 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003739}
3740
3741char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003742PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003743{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3745}
3746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003747Py_UNICODE *
3748PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003750 const unsigned char *one_byte;
3751#if SIZEOF_WCHAR_T == 4
3752 const Py_UCS2 *two_bytes;
3753#else
3754 const Py_UCS4 *four_bytes;
3755 const Py_UCS4 *ucs4_end;
3756 Py_ssize_t num_surrogates;
3757#endif
3758 wchar_t *w;
3759 wchar_t *wchar_end;
3760
3761 if (!PyUnicode_Check(unicode)) {
3762 PyErr_BadArgument();
3763 return NULL;
3764 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003765 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003767 assert(_PyUnicode_KIND(unicode) != 0);
3768 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003769
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003770 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003772 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3773 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003774 num_surrogates = 0;
3775
3776 for (; four_bytes < ucs4_end; ++four_bytes) {
3777 if (*four_bytes > 0xFFFF)
3778 ++num_surrogates;
3779 }
3780
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003781 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3782 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3783 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003784 PyErr_NoMemory();
3785 return NULL;
3786 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003787 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003789 w = _PyUnicode_WSTR(unicode);
3790 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3791 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003792 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3793 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003794 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003795 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003796 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3797 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798 }
3799 else
3800 *w = *four_bytes;
3801
3802 if (w > wchar_end) {
3803 assert(0 && "Miscalculated string end");
3804 }
3805 }
3806 *w = 0;
3807#else
3808 /* sizeof(wchar_t) == 4 */
3809 Py_FatalError("Impossible unicode object state, wstr and str "
3810 "should share memory already.");
3811 return NULL;
3812#endif
3813 }
3814 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003815 if ((size_t)_PyUnicode_LENGTH(unicode) >
3816 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3817 PyErr_NoMemory();
3818 return NULL;
3819 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003820 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3821 (_PyUnicode_LENGTH(unicode) + 1));
3822 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823 PyErr_NoMemory();
3824 return NULL;
3825 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3827 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3828 w = _PyUnicode_WSTR(unicode);
3829 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003830
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003831 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3832 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003833 for (; w < wchar_end; ++one_byte, ++w)
3834 *w = *one_byte;
3835 /* null-terminate the wstr */
3836 *w = 0;
3837 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003838 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003839#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003840 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003841 for (; w < wchar_end; ++two_bytes, ++w)
3842 *w = *two_bytes;
3843 /* null-terminate the wstr */
3844 *w = 0;
3845#else
3846 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003847 PyObject_FREE(_PyUnicode_WSTR(unicode));
3848 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 Py_FatalError("Impossible unicode object state, wstr "
3850 "and str should share memory already.");
3851 return NULL;
3852#endif
3853 }
3854 else {
3855 assert(0 && "This should never happen.");
3856 }
3857 }
3858 }
3859 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003860 *size = PyUnicode_WSTR_LENGTH(unicode);
3861 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003862}
3863
Alexander Belopolsky40018472011-02-26 01:02:56 +00003864Py_UNICODE *
3865PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003866{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003867 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003868}
3869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870
Alexander Belopolsky40018472011-02-26 01:02:56 +00003871Py_ssize_t
3872PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003873{
3874 if (!PyUnicode_Check(unicode)) {
3875 PyErr_BadArgument();
3876 goto onError;
3877 }
3878 return PyUnicode_GET_SIZE(unicode);
3879
Benjamin Peterson29060642009-01-31 22:14:21 +00003880 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003881 return -1;
3882}
3883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884Py_ssize_t
3885PyUnicode_GetLength(PyObject *unicode)
3886{
Victor Stinner07621332012-06-16 04:53:46 +02003887 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003888 PyErr_BadArgument();
3889 return -1;
3890 }
Victor Stinner07621332012-06-16 04:53:46 +02003891 if (PyUnicode_READY(unicode) == -1)
3892 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 return PyUnicode_GET_LENGTH(unicode);
3894}
3895
3896Py_UCS4
3897PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3898{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003899 void *data;
3900 int kind;
3901
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003902 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3903 PyErr_BadArgument();
3904 return (Py_UCS4)-1;
3905 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003906 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003907 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return (Py_UCS4)-1;
3909 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003910 data = PyUnicode_DATA(unicode);
3911 kind = PyUnicode_KIND(unicode);
3912 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003913}
3914
3915int
3916PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3917{
3918 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003919 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 return -1;
3921 }
Victor Stinner488fa492011-12-12 00:01:39 +01003922 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003923 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003924 PyErr_SetString(PyExc_IndexError, "string index out of range");
3925 return -1;
3926 }
Victor Stinner488fa492011-12-12 00:01:39 +01003927 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003928 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003929 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3930 PyErr_SetString(PyExc_ValueError, "character out of range");
3931 return -1;
3932 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003933 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3934 index, ch);
3935 return 0;
3936}
3937
Alexander Belopolsky40018472011-02-26 01:02:56 +00003938const char *
3939PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003940{
Victor Stinner42cb4622010-09-01 19:39:01 +00003941 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003942}
3943
Victor Stinner554f3f02010-06-16 23:33:54 +00003944/* create or adjust a UnicodeDecodeError */
3945static void
3946make_decode_exception(PyObject **exceptionObject,
3947 const char *encoding,
3948 const char *input, Py_ssize_t length,
3949 Py_ssize_t startpos, Py_ssize_t endpos,
3950 const char *reason)
3951{
3952 if (*exceptionObject == NULL) {
3953 *exceptionObject = PyUnicodeDecodeError_Create(
3954 encoding, input, length, startpos, endpos, reason);
3955 }
3956 else {
3957 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3958 goto onError;
3959 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3960 goto onError;
3961 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3962 goto onError;
3963 }
3964 return;
3965
3966onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003967 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003968}
3969
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003970#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003971/* error handling callback helper:
3972 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003973 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003974 and adjust various state variables.
3975 return 0 on success, -1 on error
3976*/
3977
Alexander Belopolsky40018472011-02-26 01:02:56 +00003978static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003979unicode_decode_call_errorhandler_wchar(
3980 const char *errors, PyObject **errorHandler,
3981 const char *encoding, const char *reason,
3982 const char **input, const char **inend, Py_ssize_t *startinpos,
3983 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3984 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003986 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003987
3988 PyObject *restuple = NULL;
3989 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003990 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003991 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003992 Py_ssize_t requiredsize;
3993 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003994 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003995 wchar_t *repwstr;
3996 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003997
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003998 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3999 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004000
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004001 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004002 *errorHandler = PyCodec_LookupError(errors);
4003 if (*errorHandler == NULL)
4004 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004005 }
4006
Victor Stinner554f3f02010-06-16 23:33:54 +00004007 make_decode_exception(exceptionObject,
4008 encoding,
4009 *input, *inend - *input,
4010 *startinpos, *endinpos,
4011 reason);
4012 if (*exceptionObject == NULL)
4013 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014
4015 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4016 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004017 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004018 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004019 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004020 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004021 }
4022 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004023 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004024
4025 /* Copy back the bytes variables, which might have been modified by the
4026 callback */
4027 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4028 if (!inputobj)
4029 goto onError;
4030 if (!PyBytes_Check(inputobj)) {
4031 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4032 }
4033 *input = PyBytes_AS_STRING(inputobj);
4034 insize = PyBytes_GET_SIZE(inputobj);
4035 *inend = *input + insize;
4036 /* we can DECREF safely, as the exception has another reference,
4037 so the object won't go away. */
4038 Py_DECREF(inputobj);
4039
4040 if (newpos<0)
4041 newpos = insize+newpos;
4042 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004043 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004044 goto onError;
4045 }
4046
4047 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4048 if (repwstr == NULL)
4049 goto onError;
4050 /* need more space? (at least enough for what we
4051 have+the replacement+the rest of the string (starting
4052 at the new input position), so we won't have to check space
4053 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004054 requiredsize = *outpos;
4055 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4056 goto overflow;
4057 requiredsize += repwlen;
4058 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4059 goto overflow;
4060 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004061 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004062 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004063 requiredsize = 2*outsize;
4064 if (unicode_resize(output, requiredsize) < 0)
4065 goto onError;
4066 }
4067 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4068 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004069 *endinpos = newpos;
4070 *inptr = *input + newpos;
4071
4072 /* we made it! */
4073 Py_XDECREF(restuple);
4074 return 0;
4075
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004076 overflow:
4077 PyErr_SetString(PyExc_OverflowError,
4078 "decoded result is too long for a Python string");
4079
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004080 onError:
4081 Py_XDECREF(restuple);
4082 return -1;
4083}
4084#endif /* HAVE_MBCS */
4085
4086static int
4087unicode_decode_call_errorhandler_writer(
4088 const char *errors, PyObject **errorHandler,
4089 const char *encoding, const char *reason,
4090 const char **input, const char **inend, Py_ssize_t *startinpos,
4091 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4092 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4093{
4094 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4095
4096 PyObject *restuple = NULL;
4097 PyObject *repunicode = NULL;
4098 Py_ssize_t insize;
4099 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004100 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004101 PyObject *inputobj = NULL;
4102
4103 if (*errorHandler == NULL) {
4104 *errorHandler = PyCodec_LookupError(errors);
4105 if (*errorHandler == NULL)
4106 goto onError;
4107 }
4108
4109 make_decode_exception(exceptionObject,
4110 encoding,
4111 *input, *inend - *input,
4112 *startinpos, *endinpos,
4113 reason);
4114 if (*exceptionObject == NULL)
4115 goto onError;
4116
4117 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4118 if (restuple == NULL)
4119 goto onError;
4120 if (!PyTuple_Check(restuple)) {
4121 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4122 goto onError;
4123 }
4124 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004125 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004126
4127 /* Copy back the bytes variables, which might have been modified by the
4128 callback */
4129 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4130 if (!inputobj)
4131 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004132 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004133 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004134 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004135 *input = PyBytes_AS_STRING(inputobj);
4136 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004137 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004138 /* we can DECREF safely, as the exception has another reference,
4139 so the object won't go away. */
4140 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004141
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004142 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004143 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004144 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004145 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004146 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004147 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004148
Victor Stinner8f674cc2013-04-17 23:02:17 +02004149 if (PyUnicode_READY(repunicode) < 0)
4150 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004151 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004152 if (replen > 1) {
4153 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004154 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004155 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4156 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4157 goto onError;
4158 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004159 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004160 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004162 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004163 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004164
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004166 Py_XDECREF(restuple);
4167 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004168
Benjamin Peterson29060642009-01-31 22:14:21 +00004169 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004170 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004171 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004172}
4173
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004174/* --- UTF-7 Codec -------------------------------------------------------- */
4175
Antoine Pitrou244651a2009-05-04 18:56:13 +00004176/* See RFC2152 for details. We encode conservatively and decode liberally. */
4177
4178/* Three simple macros defining base-64. */
4179
4180/* Is c a base-64 character? */
4181
4182#define IS_BASE64(c) \
4183 (((c) >= 'A' && (c) <= 'Z') || \
4184 ((c) >= 'a' && (c) <= 'z') || \
4185 ((c) >= '0' && (c) <= '9') || \
4186 (c) == '+' || (c) == '/')
4187
4188/* given that c is a base-64 character, what is its base-64 value? */
4189
4190#define FROM_BASE64(c) \
4191 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4192 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4193 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4194 (c) == '+' ? 62 : 63)
4195
4196/* What is the base-64 character of the bottom 6 bits of n? */
4197
4198#define TO_BASE64(n) \
4199 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4200
4201/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4202 * decoded as itself. We are permissive on decoding; the only ASCII
4203 * byte not decoding to itself is the + which begins a base64
4204 * string. */
4205
4206#define DECODE_DIRECT(c) \
4207 ((c) <= 127 && (c) != '+')
4208
4209/* The UTF-7 encoder treats ASCII characters differently according to
4210 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4211 * the above). See RFC2152. This array identifies these different
4212 * sets:
4213 * 0 : "Set D"
4214 * alphanumeric and '(),-./:?
4215 * 1 : "Set O"
4216 * !"#$%&*;<=>@[]^_`{|}
4217 * 2 : "whitespace"
4218 * ht nl cr sp
4219 * 3 : special (must be base64 encoded)
4220 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4221 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004222
Tim Petersced69f82003-09-16 20:30:58 +00004223static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004224char utf7_category[128] = {
4225/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4226 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4227/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4228 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4229/* sp ! " # $ % & ' ( ) * + , - . / */
4230 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4231/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4232 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4233/* @ A B C D E F G H I J K L M N O */
4234 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4235/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4236 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4237/* ` a b c d e f g h i j k l m n o */
4238 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4239/* p q r s t u v w x y z { | } ~ del */
4240 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004241};
4242
Antoine Pitrou244651a2009-05-04 18:56:13 +00004243/* ENCODE_DIRECT: this character should be encoded as itself. The
4244 * answer depends on whether we are encoding set O as itself, and also
4245 * on whether we are encoding whitespace as itself. RFC2152 makes it
4246 * clear that the answers to these questions vary between
4247 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004248
Antoine Pitrou244651a2009-05-04 18:56:13 +00004249#define ENCODE_DIRECT(c, directO, directWS) \
4250 ((c) < 128 && (c) > 0 && \
4251 ((utf7_category[(c)] == 0) || \
4252 (directWS && (utf7_category[(c)] == 2)) || \
4253 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004254
Alexander Belopolsky40018472011-02-26 01:02:56 +00004255PyObject *
4256PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004257 Py_ssize_t size,
4258 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004259{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004260 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4261}
4262
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263/* The decoder. The only state we preserve is our read position,
4264 * i.e. how many characters we have consumed. So if we end in the
4265 * middle of a shift sequence we have to back off the read position
4266 * and the output to the beginning of the sequence, otherwise we lose
4267 * all the shift state (seen bits, number of bits seen, high
4268 * surrogate). */
4269
Alexander Belopolsky40018472011-02-26 01:02:56 +00004270PyObject *
4271PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004272 Py_ssize_t size,
4273 const char *errors,
4274 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004275{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004276 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004277 Py_ssize_t startinpos;
4278 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004279 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004280 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 const char *errmsg = "";
4282 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004283 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004284 unsigned int base64bits = 0;
4285 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004286 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 PyObject *errorHandler = NULL;
4288 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004290 if (size == 0) {
4291 if (consumed)
4292 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004293 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004294 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004297 _PyUnicodeWriter_Init(&writer);
4298 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299
4300 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 e = s + size;
4302
4303 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004304 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004305 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004306 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307
Antoine Pitrou244651a2009-05-04 18:56:13 +00004308 if (inShift) { /* in a base-64 section */
4309 if (IS_BASE64(ch)) { /* consume a base-64 character */
4310 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4311 base64bits += 6;
4312 s++;
4313 if (base64bits >= 16) {
4314 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004315 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004316 base64bits -= 16;
4317 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004318 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 if (surrogate) {
4320 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004321 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4322 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004323 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004324 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004326 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004327 }
4328 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004329 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004330 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004331 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004332 }
4333 }
Victor Stinner551ac952011-11-29 22:58:13 +01004334 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004335 /* first surrogate */
4336 surrogate = outCh;
4337 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004338 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004339 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004340 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004341 }
4342 }
4343 }
4344 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345 inShift = 0;
4346 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004347 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004348 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004349 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004350 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004351 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 if (base64bits > 0) { /* left-over bits */
4353 if (base64bits >= 6) {
4354 /* We've seen at least one base-64 character */
4355 errmsg = "partial character in shift sequence";
4356 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004357 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 else {
4359 /* Some bits remain; they should be zero */
4360 if (base64buffer != 0) {
4361 errmsg = "non-zero padding bits in shift sequence";
4362 goto utf7Error;
4363 }
4364 }
4365 }
4366 if (ch != '-') {
4367 /* '-' is absorbed; other terminating
4368 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004369 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004370 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004372 }
4373 }
4374 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004375 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 s++; /* consume '+' */
4377 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004379 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004380 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 }
4382 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004384 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004386 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004387 }
4388 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004391 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004392 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004393 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004394 else {
4395 startinpos = s-starts;
4396 s++;
4397 errmsg = "unexpected special character";
4398 goto utf7Error;
4399 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004401utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004402 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004403 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 errors, &errorHandler,
4405 "utf7", errmsg,
4406 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004407 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004408 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004409 }
4410
Antoine Pitrou244651a2009-05-04 18:56:13 +00004411 /* end of string */
4412
4413 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4414 /* if we're in an inconsistent state, that's an error */
4415 if (surrogate ||
4416 (base64bits >= 6) ||
4417 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004419 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 errors, &errorHandler,
4421 "utf7", "unterminated shift sequence",
4422 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004423 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 goto onError;
4425 if (s < e)
4426 goto restart;
4427 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004428 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429
4430 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004431 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004433 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004434 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004435 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004436 writer.kind, writer.data, shiftOutStart);
4437 Py_XDECREF(errorHandler);
4438 Py_XDECREF(exc);
4439 _PyUnicodeWriter_Dealloc(&writer);
4440 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004441 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004442 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 }
4444 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004445 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004447 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004448
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004449 Py_XDECREF(errorHandler);
4450 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004451 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452
Benjamin Peterson29060642009-01-31 22:14:21 +00004453 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004454 Py_XDECREF(errorHandler);
4455 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004456 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004457 return NULL;
4458}
4459
4460
Alexander Belopolsky40018472011-02-26 01:02:56 +00004461PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004462_PyUnicode_EncodeUTF7(PyObject *str,
4463 int base64SetO,
4464 int base64WhiteSpace,
4465 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004466{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004467 int kind;
4468 void *data;
4469 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004470 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004472 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004473 unsigned int base64bits = 0;
4474 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004475 char * out;
4476 char * start;
4477
Benjamin Petersonbac79492012-01-14 13:34:47 -05004478 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004479 return NULL;
4480 kind = PyUnicode_KIND(str);
4481 data = PyUnicode_DATA(str);
4482 len = PyUnicode_GET_LENGTH(str);
4483
4484 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004486
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004487 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004488 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004489 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004490 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004491 if (v == NULL)
4492 return NULL;
4493
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004494 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004496 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497
Antoine Pitrou244651a2009-05-04 18:56:13 +00004498 if (inShift) {
4499 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4500 /* shifting out */
4501 if (base64bits) { /* output remaining bits */
4502 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4503 base64buffer = 0;
4504 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 }
4506 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507 /* Characters not in the BASE64 set implicitly unshift the sequence
4508 so no '-' is required, except if the character is itself a '-' */
4509 if (IS_BASE64(ch) || ch == '-') {
4510 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 *out++ = (char) ch;
4513 }
4514 else {
4515 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004516 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004518 else { /* not in a shift sequence */
4519 if (ch == '+') {
4520 *out++ = '+';
4521 *out++ = '-';
4522 }
4523 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4524 *out++ = (char) ch;
4525 }
4526 else {
4527 *out++ = '+';
4528 inShift = 1;
4529 goto encode_char;
4530 }
4531 }
4532 continue;
4533encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004535 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004536
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 /* code first surrogate */
4538 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004539 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004540 while (base64bits >= 6) {
4541 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4542 base64bits -= 6;
4543 }
4544 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004545 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004546 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 base64bits += 16;
4548 base64buffer = (base64buffer << 16) | ch;
4549 while (base64bits >= 6) {
4550 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4551 base64bits -= 6;
4552 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004553 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 if (base64bits)
4555 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4556 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004557 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004558 if (_PyBytes_Resize(&v, out - start) < 0)
4559 return NULL;
4560 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004561}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004562PyObject *
4563PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4564 Py_ssize_t size,
4565 int base64SetO,
4566 int base64WhiteSpace,
4567 const char *errors)
4568{
4569 PyObject *result;
4570 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4571 if (tmp == NULL)
4572 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004573 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004574 base64WhiteSpace, errors);
4575 Py_DECREF(tmp);
4576 return result;
4577}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578
Antoine Pitrou244651a2009-05-04 18:56:13 +00004579#undef IS_BASE64
4580#undef FROM_BASE64
4581#undef TO_BASE64
4582#undef DECODE_DIRECT
4583#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584
Guido van Rossumd57fd912000-03-10 22:53:23 +00004585/* --- UTF-8 Codec -------------------------------------------------------- */
4586
Alexander Belopolsky40018472011-02-26 01:02:56 +00004587PyObject *
4588PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004589 Py_ssize_t size,
4590 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004591{
Walter Dörwald69652032004-09-07 20:24:22 +00004592 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4593}
4594
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004595#include "stringlib/asciilib.h"
4596#include "stringlib/codecs.h"
4597#include "stringlib/undef.h"
4598
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004599#include "stringlib/ucs1lib.h"
4600#include "stringlib/codecs.h"
4601#include "stringlib/undef.h"
4602
4603#include "stringlib/ucs2lib.h"
4604#include "stringlib/codecs.h"
4605#include "stringlib/undef.h"
4606
4607#include "stringlib/ucs4lib.h"
4608#include "stringlib/codecs.h"
4609#include "stringlib/undef.h"
4610
Antoine Pitrouab868312009-01-10 15:40:25 +00004611/* Mask to quickly check whether a C 'long' contains a
4612 non-ASCII, UTF8-encoded char. */
4613#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004614# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004615#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004616# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004617#else
4618# error C 'long' size should be either 4 or 8!
4619#endif
4620
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004621static Py_ssize_t
4622ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004623{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004624 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004625 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004626
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004627 /*
4628 * Issue #17237: m68k is a bit different from most architectures in
4629 * that objects do not use "natural alignment" - for example, int and
4630 * long are only aligned at 2-byte boundaries. Therefore the assert()
4631 * won't work; also, tests have shown that skipping the "optimised
4632 * version" will even speed up m68k.
4633 */
4634#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004636 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4637 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004638 /* Fast path, see in STRINGLIB(utf8_decode) for
4639 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004640 /* Help allocation */
4641 const char *_p = p;
4642 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004643 while (_p < aligned_end) {
4644 unsigned long value = *(const unsigned long *) _p;
4645 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004646 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004647 *((unsigned long *)q) = value;
4648 _p += SIZEOF_LONG;
4649 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004650 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004651 p = _p;
4652 while (p < end) {
4653 if ((unsigned char)*p & 0x80)
4654 break;
4655 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004656 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004658 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004659#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004660#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004661 while (p < end) {
4662 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4663 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004664 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004665 /* Help allocation */
4666 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004667 while (_p < aligned_end) {
4668 unsigned long value = *(unsigned long *) _p;
4669 if (value & ASCII_CHAR_MASK)
4670 break;
4671 _p += SIZEOF_LONG;
4672 }
4673 p = _p;
4674 if (_p == end)
4675 break;
4676 }
4677 if ((unsigned char)*p & 0x80)
4678 break;
4679 ++p;
4680 }
4681 memcpy(dest, start, p - start);
4682 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004683}
Antoine Pitrouab868312009-01-10 15:40:25 +00004684
Victor Stinner785938e2011-12-11 20:09:03 +01004685PyObject *
4686PyUnicode_DecodeUTF8Stateful(const char *s,
4687 Py_ssize_t size,
4688 const char *errors,
4689 Py_ssize_t *consumed)
4690{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004691 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004692 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004693 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004694
4695 Py_ssize_t startinpos;
4696 Py_ssize_t endinpos;
4697 const char *errmsg = "";
4698 PyObject *errorHandler = NULL;
4699 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004700
4701 if (size == 0) {
4702 if (consumed)
4703 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004704 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004705 }
4706
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004707 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4708 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004709 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004710 *consumed = 1;
4711 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004712 }
4713
Victor Stinner8f674cc2013-04-17 23:02:17 +02004714 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004715 writer.min_length = size;
4716 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004717 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004718
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004719 writer.pos = ascii_decode(s, end, writer.data);
4720 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004721 while (s < end) {
4722 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004723 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004724 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004725 if (PyUnicode_IS_ASCII(writer.buffer))
4726 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004729 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004730 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 } else {
4732 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004733 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004734 }
4735
4736 switch (ch) {
4737 case 0:
4738 if (s == end || consumed)
4739 goto End;
4740 errmsg = "unexpected end of data";
4741 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004742 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 break;
4744 case 1:
4745 errmsg = "invalid start byte";
4746 startinpos = s - starts;
4747 endinpos = startinpos + 1;
4748 break;
4749 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004750 case 3:
4751 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 errmsg = "invalid continuation byte";
4753 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004754 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 break;
4756 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004757 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 goto onError;
4759 continue;
4760 }
4761
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004762 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 errors, &errorHandler,
4764 "utf-8", errmsg,
4765 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004766 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004768 }
4769
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004770End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004771 if (consumed)
4772 *consumed = s - starts;
4773
4774 Py_XDECREF(errorHandler);
4775 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004776 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004777
4778onError:
4779 Py_XDECREF(errorHandler);
4780 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004781 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004782 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004783}
4784
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004785#ifdef __APPLE__
4786
4787/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004788 used to decode the command line arguments on Mac OS X.
4789
4790 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004791 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004792
4793wchar_t*
4794_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4795{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004796 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004797 wchar_t *unicode;
4798 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004799
4800 /* Note: size will always be longer than the resulting Unicode
4801 character count */
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004802 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004803 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004804 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004805 if (!unicode)
4806 return NULL;
4807
4808 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004809 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004810 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004811 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004812 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004813#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004815#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004817#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 if (ch > 0xFF) {
4819#if SIZEOF_WCHAR_T == 4
4820 assert(0);
4821#else
4822 assert(Py_UNICODE_IS_SURROGATE(ch));
4823 /* compute and append the two surrogates: */
4824 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4825 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4826#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004827 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 else {
4829 if (!ch && s == e)
4830 break;
4831 /* surrogateescape */
4832 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4833 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004834 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004836 return unicode;
4837}
4838
4839#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004841/* Primary internal function which creates utf8 encoded bytes objects.
4842
4843 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004844 and allocate exactly as much space needed at the end. Else allocate the
4845 maximum possible needed (4 result bytes per Unicode character), and return
4846 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004847*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004848PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004849_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004850{
Victor Stinner6099a032011-12-18 14:22:26 +01004851 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 void *data;
4853 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004855 if (!PyUnicode_Check(unicode)) {
4856 PyErr_BadArgument();
4857 return NULL;
4858 }
4859
4860 if (PyUnicode_READY(unicode) == -1)
4861 return NULL;
4862
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004863 if (PyUnicode_UTF8(unicode))
4864 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4865 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866
4867 kind = PyUnicode_KIND(unicode);
4868 data = PyUnicode_DATA(unicode);
4869 size = PyUnicode_GET_LENGTH(unicode);
4870
Benjamin Petersonead6b532011-12-20 17:23:42 -06004871 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004872 default:
4873 assert(0);
4874 case PyUnicode_1BYTE_KIND:
4875 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4876 assert(!PyUnicode_IS_ASCII(unicode));
4877 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4878 case PyUnicode_2BYTE_KIND:
4879 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4880 case PyUnicode_4BYTE_KIND:
4881 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004882 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004883}
4884
Alexander Belopolsky40018472011-02-26 01:02:56 +00004885PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004886PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4887 Py_ssize_t size,
4888 const char *errors)
4889{
4890 PyObject *v, *unicode;
4891
4892 unicode = PyUnicode_FromUnicode(s, size);
4893 if (unicode == NULL)
4894 return NULL;
4895 v = _PyUnicode_AsUTF8String(unicode, errors);
4896 Py_DECREF(unicode);
4897 return v;
4898}
4899
4900PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004901PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004903 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004904}
4905
Walter Dörwald41980ca2007-08-16 21:55:45 +00004906/* --- UTF-32 Codec ------------------------------------------------------- */
4907
4908PyObject *
4909PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004910 Py_ssize_t size,
4911 const char *errors,
4912 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004913{
4914 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4915}
4916
4917PyObject *
4918PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004919 Py_ssize_t size,
4920 const char *errors,
4921 int *byteorder,
4922 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004923{
4924 const char *starts = s;
4925 Py_ssize_t startinpos;
4926 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004927 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004928 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004929 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004930 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932 PyObject *errorHandler = NULL;
4933 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935 q = (unsigned char *)s;
4936 e = q + size;
4937
4938 if (byteorder)
4939 bo = *byteorder;
4940
4941 /* Check for BOM marks (U+FEFF) in the input and adjust current
4942 byte order setting accordingly. In native mode, the leading BOM
4943 mark is skipped, in all other modes, it is copied to the output
4944 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004945 if (bo == 0 && size >= 4) {
4946 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4947 if (bom == 0x0000FEFF) {
4948 bo = -1;
4949 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004951 else if (bom == 0xFFFE0000) {
4952 bo = 1;
4953 q += 4;
4954 }
4955 if (byteorder)
4956 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004957 }
4958
Victor Stinnere64322e2012-10-30 23:12:47 +01004959 if (q == e) {
4960 if (consumed)
4961 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004962 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963 }
4964
Victor Stinnere64322e2012-10-30 23:12:47 +01004965#ifdef WORDS_BIGENDIAN
4966 le = bo < 0;
4967#else
4968 le = bo <= 0;
4969#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004970 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004971
Victor Stinner8f674cc2013-04-17 23:02:17 +02004972 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004973 writer.min_length = (e - q + 3) / 4;
4974 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004975 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004976
Victor Stinnere64322e2012-10-30 23:12:47 +01004977 while (1) {
4978 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004979 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004980
Victor Stinnere64322e2012-10-30 23:12:47 +01004981 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 enum PyUnicode_Kind kind = writer.kind;
4983 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004984 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004985 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004986 if (le) {
4987 do {
4988 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4989 if (ch > maxch)
4990 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004991 if (kind != PyUnicode_1BYTE_KIND &&
4992 Py_UNICODE_IS_SURROGATE(ch))
4993 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004995 q += 4;
4996 } while (q <= last);
4997 }
4998 else {
4999 do {
5000 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5001 if (ch > maxch)
5002 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005003 if (kind != PyUnicode_1BYTE_KIND &&
5004 Py_UNICODE_IS_SURROGATE(ch))
5005 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005006 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005007 q += 4;
5008 } while (q <= last);
5009 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005010 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005011 }
5012
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005013 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005014 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005015 startinpos = ((const char *)q) - starts;
5016 endinpos = startinpos + 4;
5017 }
5018 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005019 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005021 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005022 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005023 startinpos = ((const char *)q) - starts;
5024 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005026 else {
5027 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005028 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005029 goto onError;
5030 q += 4;
5031 continue;
5032 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005033 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005034 startinpos = ((const char *)q) - starts;
5035 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005037
5038 /* The remaining input chars are ignored if the callback
5039 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005040 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005041 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005042 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005043 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005044 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005046 }
5047
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 Py_XDECREF(errorHandler);
5052 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005053 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054
Benjamin Peterson29060642009-01-31 22:14:21 +00005055 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005056 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 Py_XDECREF(errorHandler);
5058 Py_XDECREF(exc);
5059 return NULL;
5060}
5061
5062PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005063_PyUnicode_EncodeUTF32(PyObject *str,
5064 const char *errors,
5065 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066{
Serhiy Storchaka30793282014-01-04 22:44:01 +02005067 int kind;
5068 void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005069 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005070 PyObject *v;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005071 unsigned char *p;
5072 Py_ssize_t nsize, i;
5073 /* Offsets from p for storing byte pairs in the right order. */
Christian Heimes743e0cd2012-10-17 23:52:17 +02005074#if PY_LITTLE_ENDIAN
Serhiy Storchaka30793282014-01-04 22:44:01 +02005075 int iorder[] = {0, 1, 2, 3};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005076#else
Serhiy Storchaka30793282014-01-04 22:44:01 +02005077 int iorder[] = {3, 2, 1, 0};
Walter Dörwald41980ca2007-08-16 21:55:45 +00005078#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005079 const char *encoding;
5080 PyObject *errorHandler = NULL;
5081 PyObject *exc = NULL;
5082 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083
Serhiy Storchaka30793282014-01-04 22:44:01 +02005084#define STORECHAR(CH) \
5085 do { \
5086 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5087 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5088 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5089 p[iorder[0]] = (CH) & 0xff; \
5090 p += 4; \
5091 } while(0)
5092
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005093 if (!PyUnicode_Check(str)) {
5094 PyErr_BadArgument();
5095 return NULL;
5096 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005097 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005098 return NULL;
5099 kind = PyUnicode_KIND(str);
5100 data = PyUnicode_DATA(str);
5101 len = PyUnicode_GET_LENGTH(str);
5102
Serhiy Storchaka583a9392014-01-04 19:25:37 +02005103 nsize = len + (byteorder == 0);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005104 if (nsize > PY_SSIZE_T_MAX / 4)
5105 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005106 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107 if (v == NULL)
5108 return NULL;
5109
Serhiy Storchaka30793282014-01-04 22:44:01 +02005110 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005111 if (byteorder == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005112 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005113 if (len == 0)
Serhiy Storchaka30793282014-01-04 22:44:01 +02005114 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115
Serhiy Storchaka30793282014-01-04 22:44:01 +02005116 if (byteorder == -1) {
5117 /* force LE */
5118 iorder[0] = 0;
5119 iorder[1] = 1;
5120 iorder[2] = 2;
5121 iorder[3] = 3;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005122 encoding = "utf-32-le";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005123 }
5124 else if (byteorder == 1) {
5125 /* force BE */
5126 iorder[0] = 3;
5127 iorder[1] = 2;
5128 iorder[2] = 1;
5129 iorder[3] = 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005130 encoding = "utf-32-be";
Serhiy Storchaka30793282014-01-04 22:44:01 +02005131 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005132 else
5133 encoding = "utf-32";
5134
5135 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005136 for (i = 0; i < len; i++)
5137 STORECHAR(PyUnicode_READ(kind, data, i));
5138 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005139 }
5140
Serhiy Storchaka30793282014-01-04 22:44:01 +02005141 for (i = 0; i < len;) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005142 Py_ssize_t repsize, moreunits;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005143 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5144 i++;
5145 assert(ch <= MAX_UNICODE);
5146 if (!Py_UNICODE_IS_SURROGATE(ch)) {
5147 STORECHAR(ch);
5148 continue;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005149 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005150
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005151 rep = unicode_encode_call_errorhandler(
5152 errors, &errorHandler,
5153 encoding, "surrogates not allowed",
Serhiy Storchaka30793282014-01-04 22:44:01 +02005154 str, &exc, i-1, i, &i);
5155
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005156 if (!rep)
5157 goto error;
5158
5159 if (PyBytes_Check(rep)) {
5160 repsize = PyBytes_GET_SIZE(rep);
5161 if (repsize & 3) {
5162 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005163 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005164 "surrogates not allowed");
5165 goto error;
5166 }
5167 moreunits = repsize / 4;
5168 }
5169 else {
5170 assert(PyUnicode_Check(rep));
5171 if (PyUnicode_READY(rep) < 0)
5172 goto error;
5173 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5174 if (!PyUnicode_IS_ASCII(rep)) {
5175 raise_encode_exception(&exc, encoding,
Serhiy Storchaka30793282014-01-04 22:44:01 +02005176 str, i - 1, i,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005177 "surrogates not allowed");
5178 goto error;
5179 }
5180 }
5181
5182 /* four bytes are reserved for each surrogate */
5183 if (moreunits > 1) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005184 Py_ssize_t outpos = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005185 Py_ssize_t morebytes = 4 * (moreunits - 1);
5186 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5187 /* integer overflow */
5188 PyErr_NoMemory();
5189 goto error;
5190 }
5191 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5192 goto error;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005193 p = (unsigned char*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005194 }
5195
5196 if (PyBytes_Check(rep)) {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005197 Py_MEMCPY(p, PyBytes_AS_STRING(rep), repsize);
5198 p += repsize;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005199 } else /* rep is unicode */ {
Serhiy Storchaka30793282014-01-04 22:44:01 +02005200 const Py_UCS1 *repdata;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka30793282014-01-04 22:44:01 +02005202 repdata = PyUnicode_1BYTE_DATA(rep);
5203 while (repsize--) {
5204 Py_UCS4 ch = *repdata++;
5205 STORECHAR(ch);
5206 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005207 }
5208
5209 Py_CLEAR(rep);
5210 }
5211
5212 /* Cut back to size actually needed. This is necessary for, for example,
5213 encoding of a string containing isolated surrogates and the 'ignore'
5214 handler is used. */
Serhiy Storchaka30793282014-01-04 22:44:01 +02005215 nsize = p - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005216 if (nsize != PyBytes_GET_SIZE(v))
5217 _PyBytes_Resize(&v, nsize);
5218 Py_XDECREF(errorHandler);
5219 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005220 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005221 error:
5222 Py_XDECREF(rep);
5223 Py_XDECREF(errorHandler);
5224 Py_XDECREF(exc);
5225 Py_XDECREF(v);
5226 return NULL;
Serhiy Storchaka30793282014-01-04 22:44:01 +02005227#undef STORECHAR
Walter Dörwald41980ca2007-08-16 21:55:45 +00005228}
5229
Alexander Belopolsky40018472011-02-26 01:02:56 +00005230PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005231PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5232 Py_ssize_t size,
5233 const char *errors,
5234 int byteorder)
5235{
5236 PyObject *result;
5237 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5238 if (tmp == NULL)
5239 return NULL;
5240 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5241 Py_DECREF(tmp);
5242 return result;
5243}
5244
5245PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005246PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005247{
Victor Stinnerb960b342011-11-20 19:12:52 +01005248 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249}
5250
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251/* --- UTF-16 Codec ------------------------------------------------------- */
5252
Tim Peters772747b2001-08-09 22:21:55 +00005253PyObject *
5254PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 Py_ssize_t size,
5256 const char *errors,
5257 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005258{
Walter Dörwald69652032004-09-07 20:24:22 +00005259 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5260}
5261
5262PyObject *
5263PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005264 Py_ssize_t size,
5265 const char *errors,
5266 int *byteorder,
5267 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005268{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005269 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005270 Py_ssize_t startinpos;
5271 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005272 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005273 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005274 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005275 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005276 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005277 PyObject *errorHandler = NULL;
5278 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005279 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005280
Tim Peters772747b2001-08-09 22:21:55 +00005281 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005282 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005283
5284 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005285 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005286
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005287 /* Check for BOM marks (U+FEFF) in the input and adjust current
5288 byte order setting accordingly. In native mode, the leading BOM
5289 mark is skipped, in all other modes, it is copied to the output
5290 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005291 if (bo == 0 && size >= 2) {
5292 const Py_UCS4 bom = (q[1] << 8) | q[0];
5293 if (bom == 0xFEFF) {
5294 q += 2;
5295 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005296 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005297 else if (bom == 0xFFFE) {
5298 q += 2;
5299 bo = 1;
5300 }
5301 if (byteorder)
5302 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005303 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005304
Antoine Pitrou63065d72012-05-15 23:48:04 +02005305 if (q == e) {
5306 if (consumed)
5307 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005308 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005309 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005310
Christian Heimes743e0cd2012-10-17 23:52:17 +02005311#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005312 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005313 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005314#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005316 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005317#endif
Tim Peters772747b2001-08-09 22:21:55 +00005318
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 /* Note: size will always be longer than the resulting Unicode
5320 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005321 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005322 writer.min_length = (e - q + 1) / 2;
5323 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005324 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005325
Antoine Pitrou63065d72012-05-15 23:48:04 +02005326 while (1) {
5327 Py_UCS4 ch = 0;
5328 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005329 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005330 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005332 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005333 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005334 native_ordering);
5335 else
5336 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005337 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005338 native_ordering);
5339 } else if (kind == PyUnicode_2BYTE_KIND) {
5340 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005341 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005342 native_ordering);
5343 } else {
5344 assert(kind == PyUnicode_4BYTE_KIND);
5345 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005346 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005347 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005348 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005349 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005350
Antoine Pitrou63065d72012-05-15 23:48:04 +02005351 switch (ch)
5352 {
5353 case 0:
5354 /* remaining byte at the end? (size should be even) */
5355 if (q == e || consumed)
5356 goto End;
5357 errmsg = "truncated data";
5358 startinpos = ((const char *)q) - starts;
5359 endinpos = ((const char *)e) - starts;
5360 break;
5361 /* The remaining input chars are ignored if the callback
5362 chooses to skip the input */
5363 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005364 q -= 2;
5365 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005366 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005368 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369 endinpos = ((const char *)e) - starts;
5370 break;
5371 case 2:
5372 errmsg = "illegal encoding";
5373 startinpos = ((const char *)q) - 2 - starts;
5374 endinpos = startinpos + 2;
5375 break;
5376 case 3:
5377 errmsg = "illegal UTF-16 surrogate";
5378 startinpos = ((const char *)q) - 4 - starts;
5379 endinpos = startinpos + 2;
5380 break;
5381 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005382 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005383 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 continue;
5385 }
5386
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005387 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005388 errors,
5389 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 &starts,
5392 (const char **)&e,
5393 &startinpos,
5394 &endinpos,
5395 &exc,
5396 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005397 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005399 }
5400
Antoine Pitrou63065d72012-05-15 23:48:04 +02005401End:
Walter Dörwald69652032004-09-07 20:24:22 +00005402 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005403 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005405 Py_XDECREF(errorHandler);
5406 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005407 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005410 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 Py_XDECREF(errorHandler);
5412 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413 return NULL;
5414}
5415
Tim Peters772747b2001-08-09 22:21:55 +00005416PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005417_PyUnicode_EncodeUTF16(PyObject *str,
5418 const char *errors,
5419 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005420{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005421 enum PyUnicode_Kind kind;
5422 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005423 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005424 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005425 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005426 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005427#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005428 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005429#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005430 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005431#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005432 const char *encoding;
5433 Py_ssize_t nsize, pos;
5434 PyObject *errorHandler = NULL;
5435 PyObject *exc = NULL;
5436 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005437
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005438 if (!PyUnicode_Check(str)) {
5439 PyErr_BadArgument();
5440 return NULL;
5441 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005442 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005443 return NULL;
5444 kind = PyUnicode_KIND(str);
5445 data = PyUnicode_DATA(str);
5446 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005447
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005448 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005449 if (kind == PyUnicode_4BYTE_KIND) {
5450 const Py_UCS4 *in = (const Py_UCS4 *)data;
5451 const Py_UCS4 *end = in + len;
5452 while (in < end)
5453 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005454 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005455 }
5456 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005457 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005458 nsize = len + pairs + (byteorder == 0);
5459 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460 if (v == NULL)
5461 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005462
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005464 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005465 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005466 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005467 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005468 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005469 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005470
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005471 if (kind == PyUnicode_1BYTE_KIND) {
5472 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5473 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005474 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005475
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005476 if (byteorder < 0)
5477 encoding = "utf-16-le";
5478 else if (byteorder > 0)
5479 encoding = "utf-16-be";
5480 else
5481 encoding = "utf-16";
5482
5483 pos = 0;
5484 while (pos < len) {
5485 Py_ssize_t repsize, moreunits;
5486
5487 if (kind == PyUnicode_2BYTE_KIND) {
5488 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5489 &out, native_ordering);
5490 }
5491 else {
5492 assert(kind == PyUnicode_4BYTE_KIND);
5493 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5494 &out, native_ordering);
5495 }
5496 if (pos == len)
5497 break;
5498
5499 rep = unicode_encode_call_errorhandler(
5500 errors, &errorHandler,
5501 encoding, "surrogates not allowed",
5502 str, &exc, pos, pos + 1, &pos);
5503 if (!rep)
5504 goto error;
5505
5506 if (PyBytes_Check(rep)) {
5507 repsize = PyBytes_GET_SIZE(rep);
5508 if (repsize & 1) {
5509 raise_encode_exception(&exc, encoding,
5510 str, pos - 1, pos,
5511 "surrogates not allowed");
5512 goto error;
5513 }
5514 moreunits = repsize / 2;
5515 }
5516 else {
5517 assert(PyUnicode_Check(rep));
5518 if (PyUnicode_READY(rep) < 0)
5519 goto error;
5520 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5521 if (!PyUnicode_IS_ASCII(rep)) {
5522 raise_encode_exception(&exc, encoding,
5523 str, pos - 1, pos,
5524 "surrogates not allowed");
5525 goto error;
5526 }
5527 }
5528
5529 /* two bytes are reserved for each surrogate */
5530 if (moreunits > 1) {
5531 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5532 Py_ssize_t morebytes = 2 * (moreunits - 1);
5533 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5534 /* integer overflow */
5535 PyErr_NoMemory();
5536 goto error;
5537 }
5538 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5539 goto error;
5540 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5541 }
5542
5543 if (PyBytes_Check(rep)) {
5544 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5545 out += moreunits;
5546 } else /* rep is unicode */ {
5547 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5548 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5549 &out, native_ordering);
5550 }
5551
5552 Py_CLEAR(rep);
5553 }
5554
5555 /* Cut back to size actually needed. This is necessary for, for example,
5556 encoding of a string containing isolated surrogates and the 'ignore' handler
5557 is used. */
5558 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5559 if (nsize != PyBytes_GET_SIZE(v))
5560 _PyBytes_Resize(&v, nsize);
5561 Py_XDECREF(errorHandler);
5562 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005563 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005564 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005565 error:
5566 Py_XDECREF(rep);
5567 Py_XDECREF(errorHandler);
5568 Py_XDECREF(exc);
5569 Py_XDECREF(v);
5570 return NULL;
5571#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005572}
5573
Alexander Belopolsky40018472011-02-26 01:02:56 +00005574PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005575PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5576 Py_ssize_t size,
5577 const char *errors,
5578 int byteorder)
5579{
5580 PyObject *result;
5581 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5582 if (tmp == NULL)
5583 return NULL;
5584 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5585 Py_DECREF(tmp);
5586 return result;
5587}
5588
5589PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005590PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005591{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005592 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593}
5594
5595/* --- Unicode Escape Codec ----------------------------------------------- */
5596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005597/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5598 if all the escapes in the string make it still a valid ASCII string.
5599 Returns -1 if any escapes were found which cause the string to
5600 pop out of ASCII range. Otherwise returns the length of the
5601 required buffer to hold the string.
5602 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005603static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005604length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5605{
5606 const unsigned char *p = (const unsigned char *)s;
5607 const unsigned char *end = p + size;
5608 Py_ssize_t length = 0;
5609
5610 if (size < 0)
5611 return -1;
5612
5613 for (; p < end; ++p) {
5614 if (*p > 127) {
5615 /* Non-ASCII */
5616 return -1;
5617 }
5618 else if (*p != '\\') {
5619 /* Normal character */
5620 ++length;
5621 }
5622 else {
5623 /* Backslash-escape, check next char */
5624 ++p;
5625 /* Escape sequence reaches till end of string or
5626 non-ASCII follow-up. */
5627 if (p >= end || *p > 127)
5628 return -1;
5629 switch (*p) {
5630 case '\n':
5631 /* backslash + \n result in zero characters */
5632 break;
5633 case '\\': case '\'': case '\"':
5634 case 'b': case 'f': case 't':
5635 case 'n': case 'r': case 'v': case 'a':
5636 ++length;
5637 break;
5638 case '0': case '1': case '2': case '3':
5639 case '4': case '5': case '6': case '7':
5640 case 'x': case 'u': case 'U': case 'N':
5641 /* these do not guarantee ASCII characters */
5642 return -1;
5643 default:
5644 /* count the backslash + the other character */
5645 length += 2;
5646 }
5647 }
5648 }
5649 return length;
5650}
5651
Fredrik Lundh06d12682001-01-24 07:59:11 +00005652static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005653
Alexander Belopolsky40018472011-02-26 01:02:56 +00005654PyObject *
5655PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005656 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005657 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005659 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005660 Py_ssize_t startinpos;
5661 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005664 char* message;
5665 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005666 PyObject *errorHandler = NULL;
5667 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005668 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005669
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005670 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005671 if (len == 0)
5672 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005673
5674 /* After length_of_escaped_ascii_string() there are two alternatives,
5675 either the string is pure ASCII with named escapes like \n, etc.
5676 and we determined it's exact size (common case)
5677 or it contains \x, \u, ... escape sequences. then we create a
5678 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005679 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005680 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005681 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005682 }
5683 else {
5684 /* Escaped strings will always be longer than the resulting
5685 Unicode string, so we start with size here and then reduce the
5686 length after conversion to the true value.
5687 (but if the error callback returns a long replacement string
5688 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005689 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690 }
5691
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005693 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005695
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 while (s < end) {
5697 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005698 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005699 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700
5701 /* Non-escape characters are interpreted as Unicode ordinals */
5702 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005703 x = (unsigned char)*s;
5704 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005705 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707 continue;
5708 }
5709
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005710 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005711 /* \ - Escapes */
5712 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005713 c = *s++;
5714 if (s > end)
5715 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005716
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005717 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718
Benjamin Peterson29060642009-01-31 22:14:21 +00005719 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005720#define WRITECHAR(ch) \
5721 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005722 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005723 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005724 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005725
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005727 case '\\': WRITECHAR('\\'); break;
5728 case '\'': WRITECHAR('\''); break;
5729 case '\"': WRITECHAR('\"'); break;
5730 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005731 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005732 case 'f': WRITECHAR('\014'); break;
5733 case 't': WRITECHAR('\t'); break;
5734 case 'n': WRITECHAR('\n'); break;
5735 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005737 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742 case '0': case '1': case '2': case '3':
5743 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005744 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005745 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005746 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005747 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005748 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005750 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751 break;
5752
Benjamin Peterson29060642009-01-31 22:14:21 +00005753 /* hex escapes */
5754 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005755 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 digits = 2;
5757 message = "truncated \\xXX escape";
5758 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759
Benjamin Peterson29060642009-01-31 22:14:21 +00005760 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005761 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005762 digits = 4;
5763 message = "truncated \\uXXXX escape";
5764 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005765
Benjamin Peterson29060642009-01-31 22:14:21 +00005766 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005767 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005768 digits = 8;
5769 message = "truncated \\UXXXXXXXX escape";
5770 hexescape:
5771 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005772 if (end - s < digits) {
5773 /* count only hex digits */
5774 for (; s < end; ++s) {
5775 c = (unsigned char)*s;
5776 if (!Py_ISXDIGIT(c))
5777 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005778 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005779 goto error;
5780 }
5781 for (; digits--; ++s) {
5782 c = (unsigned char)*s;
5783 if (!Py_ISXDIGIT(c))
5784 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005785 chr = (chr<<4) & ~0xF;
5786 if (c >= '0' && c <= '9')
5787 chr += c - '0';
5788 else if (c >= 'a' && c <= 'f')
5789 chr += 10 + c - 'a';
5790 else
5791 chr += 10 + c - 'A';
5792 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005793 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 /* _decoding_error will have already written into the
5795 target buffer. */
5796 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005799 message = "illegal Unicode character";
5800 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005801 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005802 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005803 break;
5804
Benjamin Peterson29060642009-01-31 22:14:21 +00005805 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005806 case 'N':
5807 message = "malformed \\N character escape";
5808 if (ucnhash_CAPI == NULL) {
5809 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5811 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005812 if (ucnhash_CAPI == NULL)
5813 goto ucnhashError;
5814 }
5815 if (*s == '{') {
5816 const char *start = s+1;
5817 /* look for the closing brace */
5818 while (*s != '}' && s < end)
5819 s++;
5820 if (s > start && s < end && *s == '}') {
5821 /* found a name. look it up in the unicode database */
5822 message = "unknown Unicode character name";
5823 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005824 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005825 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005826 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 goto store;
5828 }
5829 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005830 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005831
5832 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005833 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005834 message = "\\ at end of string";
5835 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005836 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005837 }
5838 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005839 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005840 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005841 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005842 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005843 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005844 continue;
5845
5846 error:
5847 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005848 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005849 errors, &errorHandler,
5850 "unicodeescape", message,
5851 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005852 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005853 goto onError;
5854 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005855 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005856#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005858 Py_XDECREF(errorHandler);
5859 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005860 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005861
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005863 PyErr_SetString(
5864 PyExc_UnicodeError,
5865 "\\N escapes not supported (can't load unicodedata module)"
5866 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005867 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005868 Py_XDECREF(errorHandler);
5869 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005870 return NULL;
5871
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005873 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005874 Py_XDECREF(errorHandler);
5875 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 return NULL;
5877}
5878
5879/* Return a Unicode-Escape string version of the Unicode object.
5880
5881 If quotes is true, the string is enclosed in u"" or u'' quotes as
5882 appropriate.
5883
5884*/
5885
Alexander Belopolsky40018472011-02-26 01:02:56 +00005886PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005887PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005890 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005891 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005892 int kind;
5893 void *data;
5894 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895
Ezio Melottie7f90372012-10-05 03:33:31 +03005896 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005897 escape.
5898
Ezio Melottie7f90372012-10-05 03:33:31 +03005899 For UCS1 strings it's '\xxx', 4 bytes per source character.
5900 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5901 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005902 */
5903
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005904 if (!PyUnicode_Check(unicode)) {
5905 PyErr_BadArgument();
5906 return NULL;
5907 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005908 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909 return NULL;
5910 len = PyUnicode_GET_LENGTH(unicode);
5911 kind = PyUnicode_KIND(unicode);
5912 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005913 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005914 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5915 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5916 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5917 }
5918
5919 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005920 return PyBytes_FromStringAndSize(NULL, 0);
5921
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005922 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005924
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005925 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005926 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005927 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005928 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929 if (repr == NULL)
5930 return NULL;
5931
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005932 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005934 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005935 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005936
Walter Dörwald79e913e2007-05-12 11:08:06 +00005937 /* Escape backslashes */
5938 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005939 *p++ = '\\';
5940 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005941 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005942 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005943
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005944 /* Map 21-bit characters to '\U00xxxxxx' */
5945 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005946 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005947 *p++ = '\\';
5948 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005949 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5950 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5951 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5952 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5953 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5954 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5955 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5956 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005958 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005959
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005961 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 *p++ = '\\';
5963 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005964 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5965 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5966 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5967 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005970 /* Map special whitespace to '\t', \n', '\r' */
5971 else if (ch == '\t') {
5972 *p++ = '\\';
5973 *p++ = 't';
5974 }
5975 else if (ch == '\n') {
5976 *p++ = '\\';
5977 *p++ = 'n';
5978 }
5979 else if (ch == '\r') {
5980 *p++ = '\\';
5981 *p++ = 'r';
5982 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005983
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005984 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005985 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005987 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005988 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5989 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005990 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005991
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 /* Copy everything else as-is */
5993 else
5994 *p++ = (char) ch;
5995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005997 assert(p - PyBytes_AS_STRING(repr) > 0);
5998 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5999 return NULL;
6000 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001}
6002
Alexander Belopolsky40018472011-02-26 01:02:56 +00006003PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006004PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6005 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006007 PyObject *result;
6008 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6009 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011 result = PyUnicode_AsUnicodeEscapeString(tmp);
6012 Py_DECREF(tmp);
6013 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014}
6015
6016/* --- Raw Unicode Escape Codec ------------------------------------------- */
6017
Alexander Belopolsky40018472011-02-26 01:02:56 +00006018PyObject *
6019PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006020 Py_ssize_t size,
6021 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006023 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006024 Py_ssize_t startinpos;
6025 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006026 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 const char *end;
6028 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006029 PyObject *errorHandler = NULL;
6030 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006031
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006032 if (size == 0)
6033 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006034
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 /* Escaped strings will always be longer than the resulting
6036 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006037 length after conversion to the true value. (But decoding error
6038 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006039 _PyUnicodeWriter_Init(&writer);
6040 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041
Guido van Rossumd57fd912000-03-10 22:53:23 +00006042 end = s + size;
6043 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006044 unsigned char c;
6045 Py_UCS4 x;
6046 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006047 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 /* Non-escape characters are interpreted as Unicode ordinals */
6050 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006051 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006052 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006053 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006055 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 startinpos = s-starts;
6057
6058 /* \u-escapes are only interpreted iff the number of leading
6059 backslashes if odd */
6060 bs = s;
6061 for (;s < end;) {
6062 if (*s != '\\')
6063 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006064 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006065 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006066 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 }
6068 if (((s - bs) & 1) == 0 ||
6069 s >= end ||
6070 (*s != 'u' && *s != 'U')) {
6071 continue;
6072 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006073 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006074 count = *s=='u' ? 4 : 8;
6075 s++;
6076
6077 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 for (x = 0, i = 0; i < count; ++i, ++s) {
6079 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006080 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006081 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006082 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 errors, &errorHandler,
6084 "rawunicodeescape", "truncated \\uXXXX",
6085 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006086 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 goto onError;
6088 goto nextByte;
6089 }
6090 x = (x<<4) & ~0xF;
6091 if (c >= '0' && c <= '9')
6092 x += c - '0';
6093 else if (c >= 'a' && c <= 'f')
6094 x += 10 + c - 'a';
6095 else
6096 x += 10 + c - 'A';
6097 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006098 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006099 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006100 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006101 }
6102 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006103 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006104 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006105 errors, &errorHandler,
6106 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006108 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006110 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 nextByte:
6112 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 Py_XDECREF(errorHandler);
6115 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006116 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006117
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006119 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006120 Py_XDECREF(errorHandler);
6121 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 return NULL;
6123}
6124
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006125
Alexander Belopolsky40018472011-02-26 01:02:56 +00006126PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006127PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006128{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006129 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 char *p;
6131 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006132 Py_ssize_t expandsize, pos;
6133 int kind;
6134 void *data;
6135 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006137 if (!PyUnicode_Check(unicode)) {
6138 PyErr_BadArgument();
6139 return NULL;
6140 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006141 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006142 return NULL;
6143 kind = PyUnicode_KIND(unicode);
6144 data = PyUnicode_DATA(unicode);
6145 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006146 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6147 bytes, and 1 byte characters 4. */
6148 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006149
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006152
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006153 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 if (repr == NULL)
6155 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006156 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006157 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006159 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 for (pos = 0; pos < len; pos++) {
6161 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006162 /* Map 32-bit characters to '\Uxxxxxxxx' */
6163 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006164 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006165 *p++ = '\\';
6166 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006167 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6168 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6169 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6170 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6172 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6173 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6174 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006175 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006177 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 *p++ = '\\';
6179 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006180 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6181 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6182 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6183 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 /* Copy everything else as-is */
6186 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 *p++ = (char) ch;
6188 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006189
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 assert(p > q);
6191 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006192 return NULL;
6193 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194}
6195
Alexander Belopolsky40018472011-02-26 01:02:56 +00006196PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006197PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6198 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 PyObject *result;
6201 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6202 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006203 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006204 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6205 Py_DECREF(tmp);
6206 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207}
6208
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006209/* --- Unicode Internal Codec ------------------------------------------- */
6210
Alexander Belopolsky40018472011-02-26 01:02:56 +00006211PyObject *
6212_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006213 Py_ssize_t size,
6214 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006215{
6216 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006217 Py_ssize_t startinpos;
6218 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006219 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006220 const char *end;
6221 const char *reason;
6222 PyObject *errorHandler = NULL;
6223 PyObject *exc = NULL;
6224
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006225 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006226 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006227 1))
6228 return NULL;
6229
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006230 if (size == 0)
6231 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006232
Victor Stinner8f674cc2013-04-17 23:02:17 +02006233 _PyUnicodeWriter_Init(&writer);
6234 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6235 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006237 }
6238 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006239
Victor Stinner8f674cc2013-04-17 23:02:17 +02006240 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006242 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006243 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006244 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006245 endinpos = end-starts;
6246 reason = "truncated input";
6247 goto error;
6248 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006249 /* We copy the raw representation one byte at a time because the
6250 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006251 ((char *) &uch)[0] = s[0];
6252 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006253#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006254 ((char *) &uch)[2] = s[2];
6255 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006256#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006257 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006258#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006259 /* We have to sanity check the raw data, otherwise doom looms for
6260 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006261 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006262 endinpos = s - starts + Py_UNICODE_SIZE;
6263 reason = "illegal code point (> 0x10FFFF)";
6264 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006265 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006266#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006267 s += Py_UNICODE_SIZE;
6268#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006269 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006270 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006271 Py_UNICODE uch2;
6272 ((char *) &uch2)[0] = s[0];
6273 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006274 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006275 {
Victor Stinner551ac952011-11-29 22:58:13 +01006276 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006278 }
6279 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006280#endif
6281
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006282 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006283 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006284 continue;
6285
6286 error:
6287 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006288 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006289 errors, &errorHandler,
6290 "unicode_internal", reason,
6291 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006292 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006293 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006294 }
6295
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 Py_XDECREF(errorHandler);
6297 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006298 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006299
Benjamin Peterson29060642009-01-31 22:14:21 +00006300 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006301 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006302 Py_XDECREF(errorHandler);
6303 Py_XDECREF(exc);
6304 return NULL;
6305}
6306
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307/* --- Latin-1 Codec ------------------------------------------------------ */
6308
Alexander Belopolsky40018472011-02-26 01:02:56 +00006309PyObject *
6310PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006311 Py_ssize_t size,
6312 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006313{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006315 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316}
6317
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006318/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006319static void
6320make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006321 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006322 PyObject *unicode,
6323 Py_ssize_t startpos, Py_ssize_t endpos,
6324 const char *reason)
6325{
6326 if (*exceptionObject == NULL) {
6327 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006328 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006329 encoding, unicode, startpos, endpos, reason);
6330 }
6331 else {
6332 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6333 goto onError;
6334 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6335 goto onError;
6336 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6337 goto onError;
6338 return;
6339 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006340 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006341 }
6342}
6343
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006344/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006345static void
6346raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006347 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006348 PyObject *unicode,
6349 Py_ssize_t startpos, Py_ssize_t endpos,
6350 const char *reason)
6351{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006352 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006353 encoding, unicode, startpos, endpos, reason);
6354 if (*exceptionObject != NULL)
6355 PyCodec_StrictErrors(*exceptionObject);
6356}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357
6358/* error handling callback helper:
6359 build arguments, call the callback and check the arguments,
6360 put the result into newpos and return the replacement string, which
6361 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006362static PyObject *
6363unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006364 PyObject **errorHandler,
6365 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006366 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006367 Py_ssize_t startpos, Py_ssize_t endpos,
6368 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006369{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006370 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006371 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 PyObject *restuple;
6373 PyObject *resunicode;
6374
6375 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379 }
6380
Benjamin Petersonbac79492012-01-14 13:34:47 -05006381 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006382 return NULL;
6383 len = PyUnicode_GET_LENGTH(unicode);
6384
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006385 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006386 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389
6390 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006392 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006395 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 Py_DECREF(restuple);
6397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006399 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 &resunicode, newpos)) {
6401 Py_DECREF(restuple);
6402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006403 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006404 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6405 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6406 Py_DECREF(restuple);
6407 return NULL;
6408 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410 *newpos = len + *newpos;
6411 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006412 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006413 Py_DECREF(restuple);
6414 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006415 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416 Py_INCREF(resunicode);
6417 Py_DECREF(restuple);
6418 return resunicode;
6419}
6420
Alexander Belopolsky40018472011-02-26 01:02:56 +00006421static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006423 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006424 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006426 /* input state */
6427 Py_ssize_t pos=0, size;
6428 int kind;
6429 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006430 /* output object */
6431 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006432 /* pointer into the output */
6433 char *str;
6434 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006435 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006436 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6437 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006438 PyObject *errorHandler = NULL;
6439 PyObject *exc = NULL;
6440 /* the following variable is used for caching string comparisons
6441 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6442 int known_errorHandler = -1;
6443
Benjamin Petersonbac79492012-01-14 13:34:47 -05006444 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006445 return NULL;
6446 size = PyUnicode_GET_LENGTH(unicode);
6447 kind = PyUnicode_KIND(unicode);
6448 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 /* allocate enough for a simple encoding without
6450 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006451 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006452 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006453 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006455 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006456 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457 ressize = size;
6458
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 while (pos < size) {
6460 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 /* can we encode this? */
6463 if (c<limit) {
6464 /* no overflow check, because we know that the space is enough */
6465 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006467 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 Py_ssize_t requiredsize;
6470 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006471 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006473 Py_ssize_t collstart = pos;
6474 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006476 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 ++collend;
6478 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6479 if (known_errorHandler==-1) {
6480 if ((errors==NULL) || (!strcmp(errors, "strict")))
6481 known_errorHandler = 1;
6482 else if (!strcmp(errors, "replace"))
6483 known_errorHandler = 2;
6484 else if (!strcmp(errors, "ignore"))
6485 known_errorHandler = 3;
6486 else if (!strcmp(errors, "xmlcharrefreplace"))
6487 known_errorHandler = 4;
6488 else
6489 known_errorHandler = 0;
6490 }
6491 switch (known_errorHandler) {
6492 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006493 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006494 goto onError;
6495 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006496 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 *str++ = '?'; /* fall through */
6498 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 break;
6501 case 4: /* xmlcharrefreplace */
6502 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006503 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006505 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006507 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006509 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006510 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006511 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006512 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006513 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006515 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006517 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006519 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006520 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006521 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006522 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006523 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006524 if (requiredsize > PY_SSIZE_T_MAX - incr)
6525 goto overflow;
6526 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006528 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6529 goto overflow;
6530 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006532 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 requiredsize = 2*ressize;
6534 if (_PyBytes_Resize(&res, requiredsize))
6535 goto onError;
6536 str = PyBytes_AS_STRING(res) + respos;
6537 ressize = requiredsize;
6538 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 /* generate replacement */
6540 for (i = collstart; i < collend; ++i) {
6541 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006542 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006543 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006544 break;
6545 default:
6546 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 encoding, reason, unicode, &exc,
6548 collstart, collend, &newpos);
6549 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006550 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006552 if (PyBytes_Check(repunicode)) {
6553 /* Directly copy bytes result to output. */
6554 repsize = PyBytes_Size(repunicode);
6555 if (repsize > 1) {
6556 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006557 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006558 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6559 Py_DECREF(repunicode);
6560 goto overflow;
6561 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006562 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6563 Py_DECREF(repunicode);
6564 goto onError;
6565 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006566 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006567 ressize += repsize-1;
6568 }
6569 memcpy(str, PyBytes_AsString(repunicode), repsize);
6570 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006572 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006573 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006574 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 /* need more space? (at least enough for what we
6576 have+the replacement+the rest of the string, so
6577 we won't have to check space for encodable characters) */
6578 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006579 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006580 requiredsize = respos;
6581 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6582 goto overflow;
6583 requiredsize += repsize;
6584 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6585 goto overflow;
6586 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006587 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006588 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 requiredsize = 2*ressize;
6590 if (_PyBytes_Resize(&res, requiredsize)) {
6591 Py_DECREF(repunicode);
6592 goto onError;
6593 }
6594 str = PyBytes_AS_STRING(res) + respos;
6595 ressize = requiredsize;
6596 }
6597 /* check if there is anything unencodable in the replacement
6598 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 for (i = 0; repsize-->0; ++i, ++str) {
6600 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006601 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006602 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 Py_DECREF(repunicode);
6605 goto onError;
6606 }
6607 *str = (char)c;
6608 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006610 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006611 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006612 }
6613 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006614 /* Resize if we allocated to much */
6615 size = str - PyBytes_AS_STRING(res);
6616 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006617 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006618 if (_PyBytes_Resize(&res, size) < 0)
6619 goto onError;
6620 }
6621
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006622 Py_XDECREF(errorHandler);
6623 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006624 return res;
6625
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006626 overflow:
6627 PyErr_SetString(PyExc_OverflowError,
6628 "encoded result is too long for a Python string");
6629
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006630 onError:
6631 Py_XDECREF(res);
6632 Py_XDECREF(errorHandler);
6633 Py_XDECREF(exc);
6634 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006635}
6636
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638PyObject *
6639PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 Py_ssize_t size,
6641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 PyObject *result;
6644 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6645 if (unicode == NULL)
6646 return NULL;
6647 result = unicode_encode_ucs1(unicode, errors, 256);
6648 Py_DECREF(unicode);
6649 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
Alexander Belopolsky40018472011-02-26 01:02:56 +00006652PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006653_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006654{
6655 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 PyErr_BadArgument();
6657 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006659 if (PyUnicode_READY(unicode) == -1)
6660 return NULL;
6661 /* Fast path: if it is a one-byte string, construct
6662 bytes object directly. */
6663 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6664 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6665 PyUnicode_GET_LENGTH(unicode));
6666 /* Non-Latin-1 characters present. Defer to above function to
6667 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006668 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669}
6670
6671PyObject*
6672PyUnicode_AsLatin1String(PyObject *unicode)
6673{
6674 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006675}
6676
6677/* --- 7-bit ASCII Codec -------------------------------------------------- */
6678
Alexander Belopolsky40018472011-02-26 01:02:56 +00006679PyObject *
6680PyUnicode_DecodeASCII(const char *s,
6681 Py_ssize_t size,
6682 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006683{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006685 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006686 int kind;
6687 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006688 Py_ssize_t startinpos;
6689 Py_ssize_t endinpos;
6690 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 const char *e;
6692 PyObject *errorHandler = NULL;
6693 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006694
Guido van Rossumd57fd912000-03-10 22:53:23 +00006695 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006696 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006697
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006699 if (size == 1 && (unsigned char)s[0] < 128)
6700 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006701
Victor Stinner8f674cc2013-04-17 23:02:17 +02006702 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006703 writer.min_length = size;
6704 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006705 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006706
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006708 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006709 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006710 writer.pos = outpos;
6711 if (writer.pos == size)
6712 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006713
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006714 s += writer.pos;
6715 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006717 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006719 PyUnicode_WRITE(kind, data, writer.pos, c);
6720 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 ++s;
6722 }
6723 else {
6724 startinpos = s-starts;
6725 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006726 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 errors, &errorHandler,
6728 "ascii", "ordinal not in range(128)",
6729 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006730 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006732 kind = writer.kind;
6733 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006735 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006736 Py_XDECREF(errorHandler);
6737 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006738 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006739
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006741 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006742 Py_XDECREF(errorHandler);
6743 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 return NULL;
6745}
6746
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006748PyObject *
6749PyUnicode_EncodeASCII(const Py_UNICODE *p,
6750 Py_ssize_t size,
6751 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 PyObject *result;
6754 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6755 if (unicode == NULL)
6756 return NULL;
6757 result = unicode_encode_ucs1(unicode, errors, 128);
6758 Py_DECREF(unicode);
6759 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760}
6761
Alexander Belopolsky40018472011-02-26 01:02:56 +00006762PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006763_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764{
6765 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 PyErr_BadArgument();
6767 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006769 if (PyUnicode_READY(unicode) == -1)
6770 return NULL;
6771 /* Fast path: if it is an ASCII-only string, construct bytes object
6772 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006773 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006774 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6775 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777}
6778
6779PyObject *
6780PyUnicode_AsASCIIString(PyObject *unicode)
6781{
6782 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783}
6784
Victor Stinner99b95382011-07-04 14:23:54 +02006785#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006786
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006787/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006788
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006789#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006790#define NEED_RETRY
6791#endif
6792
Victor Stinner3a50e702011-10-18 21:21:00 +02006793#ifndef WC_ERR_INVALID_CHARS
6794# define WC_ERR_INVALID_CHARS 0x0080
6795#endif
6796
6797static char*
6798code_page_name(UINT code_page, PyObject **obj)
6799{
6800 *obj = NULL;
6801 if (code_page == CP_ACP)
6802 return "mbcs";
6803 if (code_page == CP_UTF7)
6804 return "CP_UTF7";
6805 if (code_page == CP_UTF8)
6806 return "CP_UTF8";
6807
6808 *obj = PyBytes_FromFormat("cp%u", code_page);
6809 if (*obj == NULL)
6810 return NULL;
6811 return PyBytes_AS_STRING(*obj);
6812}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006813
Victor Stinner3a50e702011-10-18 21:21:00 +02006814static DWORD
6815decode_code_page_flags(UINT code_page)
6816{
6817 if (code_page == CP_UTF7) {
6818 /* The CP_UTF7 decoder only supports flags=0 */
6819 return 0;
6820 }
6821 else
6822 return MB_ERR_INVALID_CHARS;
6823}
6824
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006825/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 * Decode a byte string from a Windows code page into unicode object in strict
6827 * mode.
6828 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006829 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6830 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006831 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006832static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006833decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006834 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006835 const char *in,
6836 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837{
Victor Stinner3a50e702011-10-18 21:21:00 +02006838 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006839 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841
6842 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006843 assert(insize > 0);
6844 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6845 if (outsize <= 0)
6846 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006847
6848 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006849 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006850 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006851 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006852 if (*v == NULL)
6853 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006854 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855 }
6856 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006859 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006861 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006862 }
6863
6864 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6866 if (outsize <= 0)
6867 goto error;
6868 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006869
Victor Stinner3a50e702011-10-18 21:21:00 +02006870error:
6871 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6872 return -2;
6873 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006874 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875}
6876
Victor Stinner3a50e702011-10-18 21:21:00 +02006877/*
6878 * Decode a byte string from a code page into unicode object with an error
6879 * handler.
6880 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006881 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 * UnicodeDecodeError exception and returns -1 on error.
6883 */
6884static int
6885decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006886 PyObject **v,
6887 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006888 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006889{
6890 const char *startin = in;
6891 const char *endin = in + size;
6892 const DWORD flags = decode_code_page_flags(code_page);
6893 /* Ideally, we should get reason from FormatMessage. This is the Windows
6894 2000 English version of the message. */
6895 const char *reason = "No mapping for the Unicode character exists "
6896 "in the target code page.";
6897 /* each step cannot decode more than 1 character, but a character can be
6898 represented as a surrogate pair */
6899 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006900 int insize;
6901 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 PyObject *errorHandler = NULL;
6903 PyObject *exc = NULL;
6904 PyObject *encoding_obj = NULL;
6905 char *encoding;
6906 DWORD err;
6907 int ret = -1;
6908
6909 assert(size > 0);
6910
6911 encoding = code_page_name(code_page, &encoding_obj);
6912 if (encoding == NULL)
6913 return -1;
6914
Victor Stinner7d00cc12014-03-17 23:08:06 +01006915 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006916 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6917 UnicodeDecodeError. */
6918 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6919 if (exc != NULL) {
6920 PyCodec_StrictErrors(exc);
6921 Py_CLEAR(exc);
6922 }
6923 goto error;
6924 }
6925
6926 if (*v == NULL) {
6927 /* Create unicode object */
6928 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6929 PyErr_NoMemory();
6930 goto error;
6931 }
Victor Stinnerab595942011-12-17 04:59:06 +01006932 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006933 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006934 if (*v == NULL)
6935 goto error;
6936 startout = PyUnicode_AS_UNICODE(*v);
6937 }
6938 else {
6939 /* Extend unicode object */
6940 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6941 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6942 PyErr_NoMemory();
6943 goto error;
6944 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006945 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006946 goto error;
6947 startout = PyUnicode_AS_UNICODE(*v) + n;
6948 }
6949
6950 /* Decode the byte string character per character */
6951 out = startout;
6952 while (in < endin)
6953 {
6954 /* Decode a character */
6955 insize = 1;
6956 do
6957 {
6958 outsize = MultiByteToWideChar(code_page, flags,
6959 in, insize,
6960 buffer, Py_ARRAY_LENGTH(buffer));
6961 if (outsize > 0)
6962 break;
6963 err = GetLastError();
6964 if (err != ERROR_NO_UNICODE_TRANSLATION
6965 && err != ERROR_INSUFFICIENT_BUFFER)
6966 {
6967 PyErr_SetFromWindowsErr(0);
6968 goto error;
6969 }
6970 insize++;
6971 }
6972 /* 4=maximum length of a UTF-8 sequence */
6973 while (insize <= 4 && (in + insize) <= endin);
6974
6975 if (outsize <= 0) {
6976 Py_ssize_t startinpos, endinpos, outpos;
6977
Victor Stinner7d00cc12014-03-17 23:08:06 +01006978 /* last character in partial decode? */
6979 if (in + insize >= endin && !final)
6980 break;
6981
Victor Stinner3a50e702011-10-18 21:21:00 +02006982 startinpos = in - startin;
6983 endinpos = startinpos + 1;
6984 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006985 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006986 errors, &errorHandler,
6987 encoding, reason,
6988 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006989 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006990 {
6991 goto error;
6992 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006993 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006994 }
6995 else {
6996 in += insize;
6997 memcpy(out, buffer, outsize * sizeof(wchar_t));
6998 out += outsize;
6999 }
7000 }
7001
7002 /* write a NUL character at the end */
7003 *out = 0;
7004
7005 /* Extend unicode object */
7006 outsize = out - startout;
7007 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007008 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007009 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007010 /* (in - startin) <= size and size is an int */
7011 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007012
7013error:
7014 Py_XDECREF(encoding_obj);
7015 Py_XDECREF(errorHandler);
7016 Py_XDECREF(exc);
7017 return ret;
7018}
7019
Victor Stinner3a50e702011-10-18 21:21:00 +02007020static PyObject *
7021decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007022 const char *s, Py_ssize_t size,
7023 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007024{
Victor Stinner76a31a62011-11-04 00:05:13 +01007025 PyObject *v = NULL;
7026 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 if (code_page < 0) {
7029 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7030 return NULL;
7031 }
7032
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007033 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007034 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007035
Victor Stinner76a31a62011-11-04 00:05:13 +01007036 do
7037 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007038#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007039 if (size > INT_MAX) {
7040 chunk_size = INT_MAX;
7041 final = 0;
7042 done = 0;
7043 }
7044 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 {
7047 chunk_size = (int)size;
7048 final = (consumed == NULL);
7049 done = 1;
7050 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051
Victor Stinner76a31a62011-11-04 00:05:13 +01007052 if (chunk_size == 0 && done) {
7053 if (v != NULL)
7054 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007055 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007056 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 converted = decode_code_page_strict(code_page, &v,
7059 s, chunk_size);
7060 if (converted == -2)
7061 converted = decode_code_page_errors(code_page, &v,
7062 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007063 errors, final);
7064 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007065
7066 if (converted < 0) {
7067 Py_XDECREF(v);
7068 return NULL;
7069 }
7070
7071 if (consumed)
7072 *consumed += converted;
7073
7074 s += converted;
7075 size -= converted;
7076 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007077
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007078 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079}
7080
Alexander Belopolsky40018472011-02-26 01:02:56 +00007081PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007082PyUnicode_DecodeCodePageStateful(int code_page,
7083 const char *s,
7084 Py_ssize_t size,
7085 const char *errors,
7086 Py_ssize_t *consumed)
7087{
7088 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7089}
7090
7091PyObject *
7092PyUnicode_DecodeMBCSStateful(const char *s,
7093 Py_ssize_t size,
7094 const char *errors,
7095 Py_ssize_t *consumed)
7096{
7097 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7098}
7099
7100PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101PyUnicode_DecodeMBCS(const char *s,
7102 Py_ssize_t size,
7103 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007104{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7106}
7107
Victor Stinner3a50e702011-10-18 21:21:00 +02007108static DWORD
7109encode_code_page_flags(UINT code_page, const char *errors)
7110{
7111 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007112 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 }
7114 else if (code_page == CP_UTF7) {
7115 /* CP_UTF7 only supports flags=0 */
7116 return 0;
7117 }
7118 else {
7119 if (errors != NULL && strcmp(errors, "replace") == 0)
7120 return 0;
7121 else
7122 return WC_NO_BEST_FIT_CHARS;
7123 }
7124}
7125
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007126/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 * Encode a Unicode string to a Windows code page into a byte string in strict
7128 * mode.
7129 *
7130 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007131 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007133static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007134encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007135 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007136 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007137{
Victor Stinner554f3f02010-06-16 23:33:54 +00007138 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007139 BOOL *pusedDefaultChar = &usedDefaultChar;
7140 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007141 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007142 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007143 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 const DWORD flags = encode_code_page_flags(code_page, NULL);
7145 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007146 /* Create a substring so that we can get the UTF-16 representation
7147 of just the slice under consideration. */
7148 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007149
Martin v. Löwis3d325192011-11-04 18:23:06 +01007150 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007151
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007153 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007155 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007156
Victor Stinner2fc507f2011-11-04 20:06:39 +01007157 substring = PyUnicode_Substring(unicode, offset, offset+len);
7158 if (substring == NULL)
7159 return -1;
7160 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7161 if (p == NULL) {
7162 Py_DECREF(substring);
7163 return -1;
7164 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007165 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007166
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007167 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007169 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007170 NULL, 0,
7171 NULL, pusedDefaultChar);
7172 if (outsize <= 0)
7173 goto error;
7174 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007175 if (pusedDefaultChar && *pusedDefaultChar) {
7176 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007178 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007179
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007181 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007183 if (*outbytes == NULL) {
7184 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007185 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007186 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007188 }
7189 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007190 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 const Py_ssize_t n = PyBytes_Size(*outbytes);
7192 if (outsize > PY_SSIZE_T_MAX - n) {
7193 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007194 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007195 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007197 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7198 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007200 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202 }
7203
7204 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007206 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 out, outsize,
7208 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007209 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007210 if (outsize <= 0)
7211 goto error;
7212 if (pusedDefaultChar && *pusedDefaultChar)
7213 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007214 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007215
Victor Stinner3a50e702011-10-18 21:21:00 +02007216error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007217 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7219 return -2;
7220 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007221 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007222}
7223
Victor Stinner3a50e702011-10-18 21:21:00 +02007224/*
7225 * Encode a Unicode string to a Windows code page into a byte string using a
7226 * error handler.
7227 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007228 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 * -1 on other error.
7230 */
7231static int
7232encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007233 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007234 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007235{
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 Py_ssize_t pos = unicode_offset;
7238 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 /* Ideally, we should get reason from FormatMessage. This is the Windows
7240 2000 English version of the message. */
7241 const char *reason = "invalid character";
7242 /* 4=maximum length of a UTF-8 sequence */
7243 char buffer[4];
7244 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7245 Py_ssize_t outsize;
7246 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 PyObject *errorHandler = NULL;
7248 PyObject *exc = NULL;
7249 PyObject *encoding_obj = NULL;
7250 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007251 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 PyObject *rep;
7253 int ret = -1;
7254
7255 assert(insize > 0);
7256
7257 encoding = code_page_name(code_page, &encoding_obj);
7258 if (encoding == NULL)
7259 return -1;
7260
7261 if (errors == NULL || strcmp(errors, "strict") == 0) {
7262 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7263 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007264 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 if (exc != NULL) {
7266 PyCodec_StrictErrors(exc);
7267 Py_DECREF(exc);
7268 }
7269 Py_XDECREF(encoding_obj);
7270 return -1;
7271 }
7272
7273 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7274 pusedDefaultChar = &usedDefaultChar;
7275 else
7276 pusedDefaultChar = NULL;
7277
7278 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7279 PyErr_NoMemory();
7280 goto error;
7281 }
7282 outsize = insize * Py_ARRAY_LENGTH(buffer);
7283
7284 if (*outbytes == NULL) {
7285 /* Create string object */
7286 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7287 if (*outbytes == NULL)
7288 goto error;
7289 out = PyBytes_AS_STRING(*outbytes);
7290 }
7291 else {
7292 /* Extend string object */
7293 Py_ssize_t n = PyBytes_Size(*outbytes);
7294 if (n > PY_SSIZE_T_MAX - outsize) {
7295 PyErr_NoMemory();
7296 goto error;
7297 }
7298 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7299 goto error;
7300 out = PyBytes_AS_STRING(*outbytes) + n;
7301 }
7302
7303 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007304 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007306 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7307 wchar_t chars[2];
7308 int charsize;
7309 if (ch < 0x10000) {
7310 chars[0] = (wchar_t)ch;
7311 charsize = 1;
7312 }
7313 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007314 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7315 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007316 charsize = 2;
7317 }
7318
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007320 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 buffer, Py_ARRAY_LENGTH(buffer),
7322 NULL, pusedDefaultChar);
7323 if (outsize > 0) {
7324 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7325 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007326 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 memcpy(out, buffer, outsize);
7328 out += outsize;
7329 continue;
7330 }
7331 }
7332 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7333 PyErr_SetFromWindowsErr(0);
7334 goto error;
7335 }
7336
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 rep = unicode_encode_call_errorhandler(
7338 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007339 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007340 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 if (rep == NULL)
7342 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007343 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007344
7345 if (PyBytes_Check(rep)) {
7346 outsize = PyBytes_GET_SIZE(rep);
7347 if (outsize != 1) {
7348 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7349 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7350 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7351 Py_DECREF(rep);
7352 goto error;
7353 }
7354 out = PyBytes_AS_STRING(*outbytes) + offset;
7355 }
7356 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7357 out += outsize;
7358 }
7359 else {
7360 Py_ssize_t i;
7361 enum PyUnicode_Kind kind;
7362 void *data;
7363
Benjamin Petersonbac79492012-01-14 13:34:47 -05007364 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 Py_DECREF(rep);
7366 goto error;
7367 }
7368
7369 outsize = PyUnicode_GET_LENGTH(rep);
7370 if (outsize != 1) {
7371 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7372 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7373 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7374 Py_DECREF(rep);
7375 goto error;
7376 }
7377 out = PyBytes_AS_STRING(*outbytes) + offset;
7378 }
7379 kind = PyUnicode_KIND(rep);
7380 data = PyUnicode_DATA(rep);
7381 for (i=0; i < outsize; i++) {
7382 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7383 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007384 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 encoding, unicode,
7386 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007387 "unable to encode error handler result to ASCII");
7388 Py_DECREF(rep);
7389 goto error;
7390 }
7391 *out = (unsigned char)ch;
7392 out++;
7393 }
7394 }
7395 Py_DECREF(rep);
7396 }
7397 /* write a NUL byte */
7398 *out = 0;
7399 outsize = out - PyBytes_AS_STRING(*outbytes);
7400 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7401 if (_PyBytes_Resize(outbytes, outsize) < 0)
7402 goto error;
7403 ret = 0;
7404
7405error:
7406 Py_XDECREF(encoding_obj);
7407 Py_XDECREF(errorHandler);
7408 Py_XDECREF(exc);
7409 return ret;
7410}
7411
Victor Stinner3a50e702011-10-18 21:21:00 +02007412static PyObject *
7413encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007414 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 const char *errors)
7416{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007417 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007419 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007420 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007421
Victor Stinner29dacf22015-01-26 16:41:32 +01007422 if (!PyUnicode_Check(unicode)) {
7423 PyErr_BadArgument();
7424 return NULL;
7425 }
7426
Benjamin Petersonbac79492012-01-14 13:34:47 -05007427 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 return NULL;
7429 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007430
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 if (code_page < 0) {
7432 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7433 return NULL;
7434 }
7435
Martin v. Löwis3d325192011-11-04 18:23:06 +01007436 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007437 return PyBytes_FromStringAndSize(NULL, 0);
7438
Victor Stinner7581cef2011-11-03 22:32:33 +01007439 offset = 0;
7440 do
7441 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007442#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007443 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007444 chunks. */
7445 if (len > INT_MAX/2) {
7446 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007447 done = 0;
7448 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007449 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007450#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007451 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007452 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007453 done = 1;
7454 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007457 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007458 errors);
7459 if (ret == -2)
7460 ret = encode_code_page_errors(code_page, &outbytes,
7461 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007462 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007463 if (ret < 0) {
7464 Py_XDECREF(outbytes);
7465 return NULL;
7466 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007467
Victor Stinner7581cef2011-11-03 22:32:33 +01007468 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007469 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007470 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 return outbytes;
7473}
7474
7475PyObject *
7476PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7477 Py_ssize_t size,
7478 const char *errors)
7479{
Victor Stinner7581cef2011-11-03 22:32:33 +01007480 PyObject *unicode, *res;
7481 unicode = PyUnicode_FromUnicode(p, size);
7482 if (unicode == NULL)
7483 return NULL;
7484 res = encode_code_page(CP_ACP, unicode, errors);
7485 Py_DECREF(unicode);
7486 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007487}
7488
7489PyObject *
7490PyUnicode_EncodeCodePage(int code_page,
7491 PyObject *unicode,
7492 const char *errors)
7493{
Victor Stinner7581cef2011-11-03 22:32:33 +01007494 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007495}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007496
Alexander Belopolsky40018472011-02-26 01:02:56 +00007497PyObject *
7498PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007499{
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007501}
7502
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503#undef NEED_RETRY
7504
Victor Stinner99b95382011-07-04 14:23:54 +02007505#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007506
Guido van Rossumd57fd912000-03-10 22:53:23 +00007507/* --- Character Mapping Codec -------------------------------------------- */
7508
Victor Stinnerfb161b12013-04-18 01:44:27 +02007509static int
7510charmap_decode_string(const char *s,
7511 Py_ssize_t size,
7512 PyObject *mapping,
7513 const char *errors,
7514 _PyUnicodeWriter *writer)
7515{
7516 const char *starts = s;
7517 const char *e;
7518 Py_ssize_t startinpos, endinpos;
7519 PyObject *errorHandler = NULL, *exc = NULL;
7520 Py_ssize_t maplen;
7521 enum PyUnicode_Kind mapkind;
7522 void *mapdata;
7523 Py_UCS4 x;
7524 unsigned char ch;
7525
7526 if (PyUnicode_READY(mapping) == -1)
7527 return -1;
7528
7529 maplen = PyUnicode_GET_LENGTH(mapping);
7530 mapdata = PyUnicode_DATA(mapping);
7531 mapkind = PyUnicode_KIND(mapping);
7532
7533 e = s + size;
7534
7535 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7536 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7537 * is disabled in encoding aliases, latin1 is preferred because
7538 * its implementation is faster. */
7539 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7540 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7541 Py_UCS4 maxchar = writer->maxchar;
7542
7543 assert (writer->kind == PyUnicode_1BYTE_KIND);
7544 while (s < e) {
7545 ch = *s;
7546 x = mapdata_ucs1[ch];
7547 if (x > maxchar) {
7548 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7549 goto onError;
7550 maxchar = writer->maxchar;
7551 outdata = (Py_UCS1 *)writer->data;
7552 }
7553 outdata[writer->pos] = x;
7554 writer->pos++;
7555 ++s;
7556 }
7557 return 0;
7558 }
7559
7560 while (s < e) {
7561 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7562 enum PyUnicode_Kind outkind = writer->kind;
7563 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7564 if (outkind == PyUnicode_1BYTE_KIND) {
7565 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7566 Py_UCS4 maxchar = writer->maxchar;
7567 while (s < e) {
7568 ch = *s;
7569 x = mapdata_ucs2[ch];
7570 if (x > maxchar)
7571 goto Error;
7572 outdata[writer->pos] = x;
7573 writer->pos++;
7574 ++s;
7575 }
7576 break;
7577 }
7578 else if (outkind == PyUnicode_2BYTE_KIND) {
7579 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7580 while (s < e) {
7581 ch = *s;
7582 x = mapdata_ucs2[ch];
7583 if (x == 0xFFFE)
7584 goto Error;
7585 outdata[writer->pos] = x;
7586 writer->pos++;
7587 ++s;
7588 }
7589 break;
7590 }
7591 }
7592 ch = *s;
7593
7594 if (ch < maplen)
7595 x = PyUnicode_READ(mapkind, mapdata, ch);
7596 else
7597 x = 0xfffe; /* invalid value */
7598Error:
7599 if (x == 0xfffe)
7600 {
7601 /* undefined mapping */
7602 startinpos = s-starts;
7603 endinpos = startinpos+1;
7604 if (unicode_decode_call_errorhandler_writer(
7605 errors, &errorHandler,
7606 "charmap", "character maps to <undefined>",
7607 &starts, &e, &startinpos, &endinpos, &exc, &s,
7608 writer)) {
7609 goto onError;
7610 }
7611 continue;
7612 }
7613
7614 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7615 goto onError;
7616 ++s;
7617 }
7618 Py_XDECREF(errorHandler);
7619 Py_XDECREF(exc);
7620 return 0;
7621
7622onError:
7623 Py_XDECREF(errorHandler);
7624 Py_XDECREF(exc);
7625 return -1;
7626}
7627
7628static int
7629charmap_decode_mapping(const char *s,
7630 Py_ssize_t size,
7631 PyObject *mapping,
7632 const char *errors,
7633 _PyUnicodeWriter *writer)
7634{
7635 const char *starts = s;
7636 const char *e;
7637 Py_ssize_t startinpos, endinpos;
7638 PyObject *errorHandler = NULL, *exc = NULL;
7639 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007640 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007641
7642 e = s + size;
7643
7644 while (s < e) {
7645 ch = *s;
7646
7647 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7648 key = PyLong_FromLong((long)ch);
7649 if (key == NULL)
7650 goto onError;
7651
7652 item = PyObject_GetItem(mapping, key);
7653 Py_DECREF(key);
7654 if (item == NULL) {
7655 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7656 /* No mapping found means: mapping is undefined. */
7657 PyErr_Clear();
7658 goto Undefined;
7659 } else
7660 goto onError;
7661 }
7662
7663 /* Apply mapping */
7664 if (item == Py_None)
7665 goto Undefined;
7666 if (PyLong_Check(item)) {
7667 long value = PyLong_AS_LONG(item);
7668 if (value == 0xFFFE)
7669 goto Undefined;
7670 if (value < 0 || value > MAX_UNICODE) {
7671 PyErr_Format(PyExc_TypeError,
7672 "character mapping must be in range(0x%lx)",
7673 (unsigned long)MAX_UNICODE + 1);
7674 goto onError;
7675 }
7676
7677 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7678 goto onError;
7679 }
7680 else if (PyUnicode_Check(item)) {
7681 if (PyUnicode_READY(item) == -1)
7682 goto onError;
7683 if (PyUnicode_GET_LENGTH(item) == 1) {
7684 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7685 if (value == 0xFFFE)
7686 goto Undefined;
7687 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7688 goto onError;
7689 }
7690 else {
7691 writer->overallocate = 1;
7692 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7693 goto onError;
7694 }
7695 }
7696 else {
7697 /* wrong return value */
7698 PyErr_SetString(PyExc_TypeError,
7699 "character mapping must return integer, None or str");
7700 goto onError;
7701 }
7702 Py_CLEAR(item);
7703 ++s;
7704 continue;
7705
7706Undefined:
7707 /* undefined mapping */
7708 Py_CLEAR(item);
7709 startinpos = s-starts;
7710 endinpos = startinpos+1;
7711 if (unicode_decode_call_errorhandler_writer(
7712 errors, &errorHandler,
7713 "charmap", "character maps to <undefined>",
7714 &starts, &e, &startinpos, &endinpos, &exc, &s,
7715 writer)) {
7716 goto onError;
7717 }
7718 }
7719 Py_XDECREF(errorHandler);
7720 Py_XDECREF(exc);
7721 return 0;
7722
7723onError:
7724 Py_XDECREF(item);
7725 Py_XDECREF(errorHandler);
7726 Py_XDECREF(exc);
7727 return -1;
7728}
7729
Alexander Belopolsky40018472011-02-26 01:02:56 +00007730PyObject *
7731PyUnicode_DecodeCharmap(const char *s,
7732 Py_ssize_t size,
7733 PyObject *mapping,
7734 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007735{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007736 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007737
Guido van Rossumd57fd912000-03-10 22:53:23 +00007738 /* Default to Latin-1 */
7739 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007741
Guido van Rossumd57fd912000-03-10 22:53:23 +00007742 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007743 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007744 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007745 writer.min_length = size;
7746 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007747 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007748
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007749 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007750 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7751 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007752 }
7753 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007754 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7755 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007756 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007757 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007758
Benjamin Peterson29060642009-01-31 22:14:21 +00007759 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007760 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007761 return NULL;
7762}
7763
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007764/* Charmap encoding: the lookup table */
7765
Alexander Belopolsky40018472011-02-26 01:02:56 +00007766struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007767 PyObject_HEAD
7768 unsigned char level1[32];
7769 int count2, count3;
7770 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007771};
7772
7773static PyObject*
7774encoding_map_size(PyObject *obj, PyObject* args)
7775{
7776 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007777 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007779}
7780
7781static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007782 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 PyDoc_STR("Return the size (in bytes) of this object") },
7784 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007785};
7786
7787static void
7788encoding_map_dealloc(PyObject* o)
7789{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007790 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007791}
7792
7793static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007794 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 "EncodingMap", /*tp_name*/
7796 sizeof(struct encoding_map), /*tp_basicsize*/
7797 0, /*tp_itemsize*/
7798 /* methods */
7799 encoding_map_dealloc, /*tp_dealloc*/
7800 0, /*tp_print*/
7801 0, /*tp_getattr*/
7802 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007803 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 0, /*tp_repr*/
7805 0, /*tp_as_number*/
7806 0, /*tp_as_sequence*/
7807 0, /*tp_as_mapping*/
7808 0, /*tp_hash*/
7809 0, /*tp_call*/
7810 0, /*tp_str*/
7811 0, /*tp_getattro*/
7812 0, /*tp_setattro*/
7813 0, /*tp_as_buffer*/
7814 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7815 0, /*tp_doc*/
7816 0, /*tp_traverse*/
7817 0, /*tp_clear*/
7818 0, /*tp_richcompare*/
7819 0, /*tp_weaklistoffset*/
7820 0, /*tp_iter*/
7821 0, /*tp_iternext*/
7822 encoding_map_methods, /*tp_methods*/
7823 0, /*tp_members*/
7824 0, /*tp_getset*/
7825 0, /*tp_base*/
7826 0, /*tp_dict*/
7827 0, /*tp_descr_get*/
7828 0, /*tp_descr_set*/
7829 0, /*tp_dictoffset*/
7830 0, /*tp_init*/
7831 0, /*tp_alloc*/
7832 0, /*tp_new*/
7833 0, /*tp_free*/
7834 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835};
7836
7837PyObject*
7838PyUnicode_BuildEncodingMap(PyObject* string)
7839{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007840 PyObject *result;
7841 struct encoding_map *mresult;
7842 int i;
7843 int need_dict = 0;
7844 unsigned char level1[32];
7845 unsigned char level2[512];
7846 unsigned char *mlevel1, *mlevel2, *mlevel3;
7847 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007848 int kind;
7849 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007850 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007851 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007853 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007854 PyErr_BadArgument();
7855 return NULL;
7856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007857 kind = PyUnicode_KIND(string);
7858 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007859 length = PyUnicode_GET_LENGTH(string);
7860 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007861 memset(level1, 0xFF, sizeof level1);
7862 memset(level2, 0xFF, sizeof level2);
7863
7864 /* If there isn't a one-to-one mapping of NULL to \0,
7865 or if there are non-BMP characters, we need to use
7866 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007867 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007869 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007871 ch = PyUnicode_READ(kind, data, i);
7872 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873 need_dict = 1;
7874 break;
7875 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007876 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007877 /* unmapped character */
7878 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007879 l1 = ch >> 11;
7880 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881 if (level1[l1] == 0xFF)
7882 level1[l1] = count2++;
7883 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007884 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 }
7886
7887 if (count2 >= 0xFF || count3 >= 0xFF)
7888 need_dict = 1;
7889
7890 if (need_dict) {
7891 PyObject *result = PyDict_New();
7892 PyObject *key, *value;
7893 if (!result)
7894 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007895 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007896 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007897 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 if (!key || !value)
7899 goto failed1;
7900 if (PyDict_SetItem(result, key, value) == -1)
7901 goto failed1;
7902 Py_DECREF(key);
7903 Py_DECREF(value);
7904 }
7905 return result;
7906 failed1:
7907 Py_XDECREF(key);
7908 Py_XDECREF(value);
7909 Py_DECREF(result);
7910 return NULL;
7911 }
7912
7913 /* Create a three-level trie */
7914 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7915 16*count2 + 128*count3 - 1);
7916 if (!result)
7917 return PyErr_NoMemory();
7918 PyObject_Init(result, &EncodingMapType);
7919 mresult = (struct encoding_map*)result;
7920 mresult->count2 = count2;
7921 mresult->count3 = count3;
7922 mlevel1 = mresult->level1;
7923 mlevel2 = mresult->level23;
7924 mlevel3 = mresult->level23 + 16*count2;
7925 memcpy(mlevel1, level1, 32);
7926 memset(mlevel2, 0xFF, 16*count2);
7927 memset(mlevel3, 0, 128*count3);
7928 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007929 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007931 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7932 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 /* unmapped character */
7934 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007935 o1 = ch>>11;
7936 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 i2 = 16*mlevel1[o1] + o2;
7938 if (mlevel2[i2] == 0xFF)
7939 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007940 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007941 i3 = 128*mlevel2[i2] + o3;
7942 mlevel3[i3] = i;
7943 }
7944 return result;
7945}
7946
7947static int
Victor Stinner22168992011-11-20 17:09:18 +01007948encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949{
7950 struct encoding_map *map = (struct encoding_map*)mapping;
7951 int l1 = c>>11;
7952 int l2 = (c>>7) & 0xF;
7953 int l3 = c & 0x7F;
7954 int i;
7955
Victor Stinner22168992011-11-20 17:09:18 +01007956 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958 if (c == 0)
7959 return 0;
7960 /* level 1*/
7961 i = map->level1[l1];
7962 if (i == 0xFF) {
7963 return -1;
7964 }
7965 /* level 2*/
7966 i = map->level23[16*i+l2];
7967 if (i == 0xFF) {
7968 return -1;
7969 }
7970 /* level 3 */
7971 i = map->level23[16*map->count2 + 128*i + l3];
7972 if (i == 0) {
7973 return -1;
7974 }
7975 return i;
7976}
7977
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007978/* Lookup the character ch in the mapping. If the character
7979 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007980 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007981static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007982charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983{
Christian Heimes217cfd12007-12-02 14:31:20 +00007984 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007985 PyObject *x;
7986
7987 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007989 x = PyObject_GetItem(mapping, w);
7990 Py_DECREF(w);
7991 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007992 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7993 /* No mapping found means: mapping is undefined. */
7994 PyErr_Clear();
7995 x = Py_None;
7996 Py_INCREF(x);
7997 return x;
7998 } else
7999 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008000 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008001 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008002 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008003 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 long value = PyLong_AS_LONG(x);
8005 if (value < 0 || value > 255) {
8006 PyErr_SetString(PyExc_TypeError,
8007 "character mapping must be in range(256)");
8008 Py_DECREF(x);
8009 return NULL;
8010 }
8011 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008012 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008013 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008014 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 /* wrong return value */
8017 PyErr_Format(PyExc_TypeError,
8018 "character mapping must return integer, bytes or None, not %.400s",
8019 x->ob_type->tp_name);
8020 Py_DECREF(x);
8021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008022 }
8023}
8024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008026charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8029 /* exponentially overallocate to minimize reallocations */
8030 if (requiredsize < 2*outsize)
8031 requiredsize = 2*outsize;
8032 if (_PyBytes_Resize(outobj, requiredsize))
8033 return -1;
8034 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035}
8036
Benjamin Peterson14339b62009-01-31 16:36:08 +00008037typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008039} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008040/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008041 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008042 space is available. Return a new reference to the object that
8043 was put in the output buffer, or Py_None, if the mapping was undefined
8044 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008045 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008046static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008047charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 PyObject *rep;
8051 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008052 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053
Christian Heimes90aa7642007-12-19 02:45:37 +00008054 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008056 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057 if (res == -1)
8058 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 if (outsize<requiredsize)
8060 if (charmapencode_resize(outobj, outpos, requiredsize))
8061 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008062 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 outstart[(*outpos)++] = (char)res;
8064 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065 }
8066
8067 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008068 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008070 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 Py_DECREF(rep);
8072 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 if (PyLong_Check(rep)) {
8075 Py_ssize_t requiredsize = *outpos+1;
8076 if (outsize<requiredsize)
8077 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8078 Py_DECREF(rep);
8079 return enc_EXCEPTION;
8080 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008081 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008082 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008083 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 else {
8085 const char *repchars = PyBytes_AS_STRING(rep);
8086 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8087 Py_ssize_t requiredsize = *outpos+repsize;
8088 if (outsize<requiredsize)
8089 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8090 Py_DECREF(rep);
8091 return enc_EXCEPTION;
8092 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008093 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008094 memcpy(outstart + *outpos, repchars, repsize);
8095 *outpos += repsize;
8096 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008097 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 Py_DECREF(rep);
8099 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008100}
8101
8102/* handle an error in PyUnicode_EncodeCharmap
8103 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008104static int
8105charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008106 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008107 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008108 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008109 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008110{
8111 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008113 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008114 enum PyUnicode_Kind kind;
8115 void *data;
8116 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008117 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008118 Py_ssize_t collstartpos = *inpos;
8119 Py_ssize_t collendpos = *inpos+1;
8120 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 char *encoding = "charmap";
8122 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008124 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008125 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126
Benjamin Petersonbac79492012-01-14 13:34:47 -05008127 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008128 return -1;
8129 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 /* find all unencodable characters */
8131 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008132 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008133 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008134 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008135 val = encoding_map_lookup(ch, mapping);
8136 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 break;
8138 ++collendpos;
8139 continue;
8140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008142 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8143 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 if (rep==NULL)
8145 return -1;
8146 else if (rep!=Py_None) {
8147 Py_DECREF(rep);
8148 break;
8149 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008150 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 }
8153 /* cache callback name lookup
8154 * (if not done yet, i.e. it's the first error) */
8155 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 if ((errors==NULL) || (!strcmp(errors, "strict")))
8157 *known_errorHandler = 1;
8158 else if (!strcmp(errors, "replace"))
8159 *known_errorHandler = 2;
8160 else if (!strcmp(errors, "ignore"))
8161 *known_errorHandler = 3;
8162 else if (!strcmp(errors, "xmlcharrefreplace"))
8163 *known_errorHandler = 4;
8164 else
8165 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008166 }
8167 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008168 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008169 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008170 return -1;
8171 case 2: /* replace */
8172 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 x = charmapencode_output('?', mapping, res, respos);
8174 if (x==enc_EXCEPTION) {
8175 return -1;
8176 }
8177 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008178 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 return -1;
8180 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008181 }
8182 /* fall through */
8183 case 3: /* ignore */
8184 *inpos = collendpos;
8185 break;
8186 case 4: /* xmlcharrefreplace */
8187 /* generate replacement (temporarily (mis)uses p) */
8188 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008189 char buffer[2+29+1+1];
8190 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008192 for (cp = buffer; *cp; ++cp) {
8193 x = charmapencode_output(*cp, mapping, res, respos);
8194 if (x==enc_EXCEPTION)
8195 return -1;
8196 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008197 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 return -1;
8199 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008200 }
8201 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008202 *inpos = collendpos;
8203 break;
8204 default:
8205 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008208 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008209 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008210 if (PyBytes_Check(repunicode)) {
8211 /* Directly copy bytes result to output. */
8212 Py_ssize_t outsize = PyBytes_Size(*res);
8213 Py_ssize_t requiredsize;
8214 repsize = PyBytes_Size(repunicode);
8215 requiredsize = *respos + repsize;
8216 if (requiredsize > outsize)
8217 /* Make room for all additional bytes. */
8218 if (charmapencode_resize(res, respos, requiredsize)) {
8219 Py_DECREF(repunicode);
8220 return -1;
8221 }
8222 memcpy(PyBytes_AsString(*res) + *respos,
8223 PyBytes_AsString(repunicode), repsize);
8224 *respos += repsize;
8225 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008226 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008227 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008228 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008230 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008231 Py_DECREF(repunicode);
8232 return -1;
8233 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008234 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008235 data = PyUnicode_DATA(repunicode);
8236 kind = PyUnicode_KIND(repunicode);
8237 for (index = 0; index < repsize; index++) {
8238 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8239 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008241 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 return -1;
8243 }
8244 else if (x==enc_FAILED) {
8245 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008246 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 return -1;
8248 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008249 }
8250 *inpos = newpos;
8251 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
8253 return 0;
8254}
8255
Alexander Belopolsky40018472011-02-26 01:02:56 +00008256PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008257_PyUnicode_EncodeCharmap(PyObject *unicode,
8258 PyObject *mapping,
8259 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008260{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 /* output object */
8262 PyObject *res = NULL;
8263 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008264 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008265 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008267 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 PyObject *errorHandler = NULL;
8269 PyObject *exc = NULL;
8270 /* the following variable is used for caching string comparisons
8271 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8272 * 3=ignore, 4=xmlcharrefreplace */
8273 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008274 void *data;
8275 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276
Benjamin Petersonbac79492012-01-14 13:34:47 -05008277 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008278 return NULL;
8279 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008280 data = PyUnicode_DATA(unicode);
8281 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008282
Guido van Rossumd57fd912000-03-10 22:53:23 +00008283 /* Default to Latin-1 */
8284 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008286
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 /* allocate enough for a simple encoding without
8288 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008289 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 if (res == NULL)
8291 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008292 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008296 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (x==enc_EXCEPTION) /* error */
8300 goto onError;
8301 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008302 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 &exc,
8304 &known_errorHandler, &errorHandler, errors,
8305 &res, &respos)) {
8306 goto onError;
8307 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 else
8310 /* done with this character => adjust input position */
8311 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008312 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008313
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008315 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008316 if (_PyBytes_Resize(&res, respos) < 0)
8317 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319 Py_XDECREF(exc);
8320 Py_XDECREF(errorHandler);
8321 return res;
8322
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 Py_XDECREF(res);
8325 Py_XDECREF(exc);
8326 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008327 return NULL;
8328}
8329
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008330/* Deprecated */
8331PyObject *
8332PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8333 Py_ssize_t size,
8334 PyObject *mapping,
8335 const char *errors)
8336{
8337 PyObject *result;
8338 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8339 if (unicode == NULL)
8340 return NULL;
8341 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8342 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008343 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344}
8345
Alexander Belopolsky40018472011-02-26 01:02:56 +00008346PyObject *
8347PyUnicode_AsCharmapString(PyObject *unicode,
8348 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008349{
8350 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008351 PyErr_BadArgument();
8352 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008354 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008355}
8356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008358static void
8359make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008360 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361 Py_ssize_t startpos, Py_ssize_t endpos,
8362 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008363{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008365 *exceptionObject = _PyUnicodeTranslateError_Create(
8366 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008367 }
8368 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8370 goto onError;
8371 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8372 goto onError;
8373 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8374 goto onError;
8375 return;
8376 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008377 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 }
8379}
8380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381/* error handling callback helper:
8382 build arguments, call the callback and check the arguments,
8383 put the result into newpos and return the replacement string, which
8384 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008385static PyObject *
8386unicode_translate_call_errorhandler(const char *errors,
8387 PyObject **errorHandler,
8388 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008390 Py_ssize_t startpos, Py_ssize_t endpos,
8391 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008393 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008395 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 PyObject *restuple;
8397 PyObject *resunicode;
8398
8399 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 }
8404
8405 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008406 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409
8410 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008413 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008415 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 Py_DECREF(restuple);
8417 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 }
8419 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 &resunicode, &i_newpos)) {
8421 Py_DECREF(restuple);
8422 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008424 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008425 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008426 else
8427 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008428 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008429 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 Py_DECREF(restuple);
8431 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008432 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433 Py_INCREF(resunicode);
8434 Py_DECREF(restuple);
8435 return resunicode;
8436}
8437
8438/* Lookup the character ch in the mapping and put the result in result,
8439 which must be decrefed by the caller.
8440 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008441static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443{
Christian Heimes217cfd12007-12-02 14:31:20 +00008444 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 PyObject *x;
8446
8447 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008449 x = PyObject_GetItem(mapping, w);
8450 Py_DECREF(w);
8451 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8453 /* No mapping found means: use 1:1 mapping. */
8454 PyErr_Clear();
8455 *result = NULL;
8456 return 0;
8457 } else
8458 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 }
8460 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 *result = x;
8462 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008464 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008465 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008466 if (value < 0 || value > MAX_UNICODE) {
8467 PyErr_Format(PyExc_ValueError,
8468 "character mapping must be in range(0x%x)",
8469 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 Py_DECREF(x);
8471 return -1;
8472 }
8473 *result = x;
8474 return 0;
8475 }
8476 else if (PyUnicode_Check(x)) {
8477 *result = x;
8478 return 0;
8479 }
8480 else {
8481 /* wrong return value */
8482 PyErr_SetString(PyExc_TypeError,
8483 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008484 Py_DECREF(x);
8485 return -1;
8486 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487}
Victor Stinner1194ea02014-04-04 19:37:40 +02008488
8489/* lookup the character, write the result into the writer.
8490 Return 1 if the result was written into the writer, return 0 if the mapping
8491 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008492static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008493charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8494 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495{
Victor Stinner1194ea02014-04-04 19:37:40 +02008496 PyObject *item;
8497
8498 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008500
8501 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008503 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008506 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008508
8509 if (item == Py_None) {
8510 Py_DECREF(item);
8511 return 0;
8512 }
8513
8514 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008515 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8516 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8517 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008518 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8519 Py_DECREF(item);
8520 return -1;
8521 }
8522 Py_DECREF(item);
8523 return 1;
8524 }
8525
8526 if (!PyUnicode_Check(item)) {
8527 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008529 }
8530
8531 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8532 Py_DECREF(item);
8533 return -1;
8534 }
8535
8536 Py_DECREF(item);
8537 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538}
8539
Victor Stinner89a76ab2014-04-05 11:44:04 +02008540static int
8541unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8542 Py_UCS1 *translate)
8543{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008544 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008545 int ret = 0;
8546
Victor Stinner89a76ab2014-04-05 11:44:04 +02008547 if (charmaptranslate_lookup(ch, mapping, &item)) {
8548 return -1;
8549 }
8550
8551 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008552 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008553 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008554 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008555 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008556 /* not found => default to 1:1 mapping */
8557 translate[ch] = ch;
8558 return 1;
8559 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008560 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008561 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008562 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8563 used it */
8564 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008565 /* invalid character or character outside ASCII:
8566 skip the fast translate */
8567 goto exit;
8568 }
8569 translate[ch] = (Py_UCS1)replace;
8570 }
8571 else if (PyUnicode_Check(item)) {
8572 Py_UCS4 replace;
8573
8574 if (PyUnicode_READY(item) == -1) {
8575 Py_DECREF(item);
8576 return -1;
8577 }
8578 if (PyUnicode_GET_LENGTH(item) != 1)
8579 goto exit;
8580
8581 replace = PyUnicode_READ_CHAR(item, 0);
8582 if (replace > 127)
8583 goto exit;
8584 translate[ch] = (Py_UCS1)replace;
8585 }
8586 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008587 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008588 goto exit;
8589 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008590 ret = 1;
8591
Benjamin Peterson1365de72014-04-07 20:15:41 -04008592 exit:
8593 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008594 return ret;
8595}
8596
8597/* Fast path for ascii => ascii translation. Return 1 if the whole string
8598 was translated into writer, return 0 if the input string was partially
8599 translated into writer, raise an exception and return -1 on error. */
8600static int
8601unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008602 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008603{
Victor Stinner872b2912014-04-05 14:27:07 +02008604 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008605 Py_ssize_t len;
8606 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008607 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008608
8609 if (PyUnicode_READY(input) == -1)
8610 return -1;
8611 if (!PyUnicode_IS_ASCII(input))
8612 return 0;
8613 len = PyUnicode_GET_LENGTH(input);
8614
Victor Stinner872b2912014-04-05 14:27:07 +02008615 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008616
8617 in = PyUnicode_1BYTE_DATA(input);
8618 end = in + len;
8619
8620 assert(PyUnicode_IS_ASCII(writer->buffer));
8621 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8622 out = PyUnicode_1BYTE_DATA(writer->buffer);
8623
Victor Stinner872b2912014-04-05 14:27:07 +02008624 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008625 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008626 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008627 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008628 int translate = unicode_fast_translate_lookup(mapping, ch,
8629 ascii_table);
8630 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008631 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008632 if (translate == 0)
8633 goto exit;
8634 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008635 }
Victor Stinner872b2912014-04-05 14:27:07 +02008636 if (ch2 == 0xfe) {
8637 if (ignore)
8638 continue;
8639 goto exit;
8640 }
8641 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008642 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008643 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008644 }
Victor Stinner872b2912014-04-05 14:27:07 +02008645 res = 1;
8646
8647exit:
8648 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8649 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008650}
8651
Alexander Belopolsky40018472011-02-26 01:02:56 +00008652PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008653_PyUnicode_TranslateCharmap(PyObject *input,
8654 PyObject *mapping,
8655 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008658 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 Py_ssize_t size, i;
8660 int kind;
8661 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008662 _PyUnicodeWriter writer;
8663 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 char *reason = "character maps to <undefined>";
8665 PyObject *errorHandler = NULL;
8666 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008667 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008668 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 PyErr_BadArgument();
8672 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008675 if (PyUnicode_READY(input) == -1)
8676 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008677 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 kind = PyUnicode_KIND(input);
8679 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680
8681 if (size == 0) {
8682 Py_INCREF(input);
8683 return input;
8684 }
8685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 /* allocate enough for a simple 1:1 translation without
8687 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008688 _PyUnicodeWriter_Init(&writer);
8689 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691
Victor Stinner872b2912014-04-05 14:27:07 +02008692 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8693
8694 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008695 if (res < 0) {
8696 _PyUnicodeWriter_Dealloc(&writer);
8697 return NULL;
8698 }
8699 if (res == 1)
8700 return _PyUnicodeWriter_Finish(&writer);
8701
Victor Stinner89a76ab2014-04-05 11:44:04 +02008702 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008705 int translate;
8706 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8707 Py_ssize_t newpos;
8708 /* startpos for collecting untranslatable chars */
8709 Py_ssize_t collstart;
8710 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008711 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008712
Victor Stinner1194ea02014-04-04 19:37:40 +02008713 ch = PyUnicode_READ(kind, data, i);
8714 translate = charmaptranslate_output(ch, mapping, &writer);
8715 if (translate < 0)
8716 goto onError;
8717
8718 if (translate != 0) {
8719 /* it worked => adjust input pointer */
8720 ++i;
8721 continue;
8722 }
8723
8724 /* untranslatable character */
8725 collstart = i;
8726 collend = i+1;
8727
8728 /* find all untranslatable characters */
8729 while (collend < size) {
8730 PyObject *x;
8731 ch = PyUnicode_READ(kind, data, collend);
8732 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008733 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 Py_XDECREF(x);
8735 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 ++collend;
8738 }
8739
8740 if (ignore) {
8741 i = collend;
8742 }
8743 else {
8744 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8745 reason, input, &exc,
8746 collstart, collend, &newpos);
8747 if (repunicode == NULL)
8748 goto onError;
8749 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008751 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008752 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008753 Py_DECREF(repunicode);
8754 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008755 }
8756 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008757 Py_XDECREF(exc);
8758 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008760
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008762 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 Py_XDECREF(exc);
8764 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765 return NULL;
8766}
8767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768/* Deprecated. Use PyUnicode_Translate instead. */
8769PyObject *
8770PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8771 Py_ssize_t size,
8772 PyObject *mapping,
8773 const char *errors)
8774{
Christian Heimes5f520f42012-09-11 14:03:25 +02008775 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8777 if (!unicode)
8778 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008779 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8780 Py_DECREF(unicode);
8781 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782}
8783
Alexander Belopolsky40018472011-02-26 01:02:56 +00008784PyObject *
8785PyUnicode_Translate(PyObject *str,
8786 PyObject *mapping,
8787 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008788{
8789 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008790
Guido van Rossumd57fd912000-03-10 22:53:23 +00008791 str = PyUnicode_FromObject(str);
8792 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008793 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008795 Py_DECREF(str);
8796 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797}
Tim Petersced69f82003-09-16 20:30:58 +00008798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008800fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801{
8802 /* No need to call PyUnicode_READY(self) because this function is only
8803 called as a callback from fixup() which does it already. */
8804 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8805 const int kind = PyUnicode_KIND(self);
8806 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008807 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008808 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008809 Py_ssize_t i;
8810
8811 for (i = 0; i < len; ++i) {
8812 ch = PyUnicode_READ(kind, data, i);
8813 fixed = 0;
8814 if (ch > 127) {
8815 if (Py_UNICODE_ISSPACE(ch))
8816 fixed = ' ';
8817 else {
8818 const int decimal = Py_UNICODE_TODECIMAL(ch);
8819 if (decimal >= 0)
8820 fixed = '0' + decimal;
8821 }
8822 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008823 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008824 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825 PyUnicode_WRITE(kind, data, i, fixed);
8826 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008827 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008828 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 }
8831
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008832 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833}
8834
8835PyObject *
8836_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8837{
8838 if (!PyUnicode_Check(unicode)) {
8839 PyErr_BadInternalCall();
8840 return NULL;
8841 }
8842 if (PyUnicode_READY(unicode) == -1)
8843 return NULL;
8844 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8845 /* If the string is already ASCII, just return the same string */
8846 Py_INCREF(unicode);
8847 return unicode;
8848 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008849 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008850}
8851
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008852PyObject *
8853PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8854 Py_ssize_t length)
8855{
Victor Stinnerf0124502011-11-21 23:12:56 +01008856 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008857 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008858 Py_UCS4 maxchar;
8859 enum PyUnicode_Kind kind;
8860 void *data;
8861
Victor Stinner99d7ad02012-02-22 13:37:39 +01008862 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008863 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008864 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008865 if (ch > 127) {
8866 int decimal = Py_UNICODE_TODECIMAL(ch);
8867 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008868 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008869 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008870 }
8871 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008872
8873 /* Copy to a new string */
8874 decimal = PyUnicode_New(length, maxchar);
8875 if (decimal == NULL)
8876 return decimal;
8877 kind = PyUnicode_KIND(decimal);
8878 data = PyUnicode_DATA(decimal);
8879 /* Iterate over code points */
8880 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008881 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008882 if (ch > 127) {
8883 int decimal = Py_UNICODE_TODECIMAL(ch);
8884 if (decimal >= 0)
8885 ch = '0' + decimal;
8886 }
8887 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008888 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008889 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008890}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008891/* --- Decimal Encoder ---------------------------------------------------- */
8892
Alexander Belopolsky40018472011-02-26 01:02:56 +00008893int
8894PyUnicode_EncodeDecimal(Py_UNICODE *s,
8895 Py_ssize_t length,
8896 char *output,
8897 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008898{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008899 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008900 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008901 enum PyUnicode_Kind kind;
8902 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008903
8904 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 PyErr_BadArgument();
8906 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008907 }
8908
Victor Stinner42bf7752011-11-21 22:52:58 +01008909 unicode = PyUnicode_FromUnicode(s, length);
8910 if (unicode == NULL)
8911 return -1;
8912
Benjamin Petersonbac79492012-01-14 13:34:47 -05008913 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008914 Py_DECREF(unicode);
8915 return -1;
8916 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008917 kind = PyUnicode_KIND(unicode);
8918 data = PyUnicode_DATA(unicode);
8919
Victor Stinnerb84d7232011-11-22 01:50:07 +01008920 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008921 PyObject *exc;
8922 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008924 Py_ssize_t startpos;
8925
8926 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008927
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008929 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008930 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008932 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008933 decimal = Py_UNICODE_TODECIMAL(ch);
8934 if (decimal >= 0) {
8935 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008936 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 continue;
8938 }
8939 if (0 < ch && ch < 256) {
8940 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008941 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 continue;
8943 }
Victor Stinner6345be92011-11-25 20:09:01 +01008944
Victor Stinner42bf7752011-11-21 22:52:58 +01008945 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008946 exc = NULL;
8947 raise_encode_exception(&exc, "decimal", unicode,
8948 startpos, startpos+1,
8949 "invalid decimal Unicode string");
8950 Py_XDECREF(exc);
8951 Py_DECREF(unicode);
8952 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008953 }
8954 /* 0-terminate the output string */
8955 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008956 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008957 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008958}
8959
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960/* --- Helpers ------------------------------------------------------------ */
8961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008963any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 Py_ssize_t start,
8965 Py_ssize_t end)
8966{
8967 int kind1, kind2, kind;
8968 void *buf1, *buf2;
8969 Py_ssize_t len1, len2, result;
8970
8971 kind1 = PyUnicode_KIND(s1);
8972 kind2 = PyUnicode_KIND(s2);
8973 kind = kind1 > kind2 ? kind1 : kind2;
8974 buf1 = PyUnicode_DATA(s1);
8975 buf2 = PyUnicode_DATA(s2);
8976 if (kind1 != kind)
8977 buf1 = _PyUnicode_AsKind(s1, kind);
8978 if (!buf1)
8979 return -2;
8980 if (kind2 != kind)
8981 buf2 = _PyUnicode_AsKind(s2, kind);
8982 if (!buf2) {
8983 if (kind1 != kind) PyMem_Free(buf1);
8984 return -2;
8985 }
8986 len1 = PyUnicode_GET_LENGTH(s1);
8987 len2 = PyUnicode_GET_LENGTH(s2);
8988
Victor Stinner794d5672011-10-10 03:21:36 +02008989 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06008990 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02008991 case PyUnicode_1BYTE_KIND:
8992 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8993 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8994 else
8995 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8996 break;
8997 case PyUnicode_2BYTE_KIND:
8998 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8999 break;
9000 case PyUnicode_4BYTE_KIND:
9001 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9002 break;
9003 default:
9004 assert(0); result = -2;
9005 }
9006 }
9007 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009008 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009009 case PyUnicode_1BYTE_KIND:
9010 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9011 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9012 else
9013 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9014 break;
9015 case PyUnicode_2BYTE_KIND:
9016 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9017 break;
9018 case PyUnicode_4BYTE_KIND:
9019 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9020 break;
9021 default:
9022 assert(0); result = -2;
9023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 }
9025
9026 if (kind1 != kind)
9027 PyMem_Free(buf1);
9028 if (kind2 != kind)
9029 PyMem_Free(buf2);
9030
9031 return result;
9032}
9033
9034Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009035_PyUnicode_InsertThousandsGrouping(
9036 PyObject *unicode, Py_ssize_t index,
9037 Py_ssize_t n_buffer,
9038 void *digits, Py_ssize_t n_digits,
9039 Py_ssize_t min_width,
9040 const char *grouping, PyObject *thousands_sep,
9041 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009042{
Victor Stinner41a863c2012-02-24 00:37:51 +01009043 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009044 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009045 Py_ssize_t thousands_sep_len;
9046 Py_ssize_t len;
9047
9048 if (unicode != NULL) {
9049 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009050 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009051 }
9052 else {
9053 kind = PyUnicode_1BYTE_KIND;
9054 data = NULL;
9055 }
9056 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9057 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9058 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9059 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009060 if (thousands_sep_kind < kind) {
9061 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9062 if (!thousands_sep_data)
9063 return -1;
9064 }
9065 else {
9066 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9067 if (!data)
9068 return -1;
9069 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009070 }
9071
Benjamin Petersonead6b532011-12-20 17:23:42 -06009072 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009074 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009075 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009076 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009077 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009078 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009079 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009080 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009081 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009082 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009083 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009084 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009085 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009086 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009087 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009088 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009089 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009090 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009092 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009093 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009094 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009095 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009096 break;
9097 default:
9098 assert(0);
9099 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009100 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009101 if (unicode != NULL && thousands_sep_kind != kind) {
9102 if (thousands_sep_kind < kind)
9103 PyMem_Free(thousands_sep_data);
9104 else
9105 PyMem_Free(data);
9106 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009107 if (unicode == NULL) {
9108 *maxchar = 127;
9109 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009110 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009111 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009112 }
9113 }
9114 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115}
9116
9117
Thomas Wouters477c8d52006-05-27 19:21:47 +00009118/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009119#define ADJUST_INDICES(start, end, len) \
9120 if (end > len) \
9121 end = len; \
9122 else if (end < 0) { \
9123 end += len; \
9124 if (end < 0) \
9125 end = 0; \
9126 } \
9127 if (start < 0) { \
9128 start += len; \
9129 if (start < 0) \
9130 start = 0; \
9131 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009132
Alexander Belopolsky40018472011-02-26 01:02:56 +00009133Py_ssize_t
9134PyUnicode_Count(PyObject *str,
9135 PyObject *substr,
9136 Py_ssize_t start,
9137 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009138{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009139 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009140 PyObject* str_obj;
9141 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009142 int kind1, kind2, kind;
9143 void *buf1 = NULL, *buf2 = NULL;
9144 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009145
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009146 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009147 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009148 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009149 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009150 if (!sub_obj) {
9151 Py_DECREF(str_obj);
9152 return -1;
9153 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009154 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009155 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 Py_DECREF(str_obj);
9157 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009158 }
Tim Petersced69f82003-09-16 20:30:58 +00009159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009160 kind1 = PyUnicode_KIND(str_obj);
9161 kind2 = PyUnicode_KIND(sub_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009162 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 buf2 = PyUnicode_DATA(sub_obj);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009165 if (kind2 != kind) {
Antoine Pitrou758153b2012-05-12 15:51:51 +02009166 if (kind2 > kind) {
9167 Py_DECREF(sub_obj);
9168 Py_DECREF(str_obj);
Antoine Pitroue45c0c52012-05-12 15:49:07 +02009169 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +02009170 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01009171 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 if (!buf2)
9174 goto onError;
9175 len1 = PyUnicode_GET_LENGTH(str_obj);
9176 len2 = PyUnicode_GET_LENGTH(sub_obj);
9177
9178 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009179 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009181 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9182 result = asciilib_count(
9183 ((Py_UCS1*)buf1) + start, end - start,
9184 buf2, len2, PY_SSIZE_T_MAX
9185 );
9186 else
9187 result = ucs1lib_count(
9188 ((Py_UCS1*)buf1) + start, end - start,
9189 buf2, len2, PY_SSIZE_T_MAX
9190 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 break;
9192 case PyUnicode_2BYTE_KIND:
9193 result = ucs2lib_count(
9194 ((Py_UCS2*)buf1) + start, end - start,
9195 buf2, len2, PY_SSIZE_T_MAX
9196 );
9197 break;
9198 case PyUnicode_4BYTE_KIND:
9199 result = ucs4lib_count(
9200 ((Py_UCS4*)buf1) + start, end - start,
9201 buf2, len2, PY_SSIZE_T_MAX
9202 );
9203 break;
9204 default:
9205 assert(0); result = 0;
9206 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009207
9208 Py_DECREF(sub_obj);
9209 Py_DECREF(str_obj);
9210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 if (kind2 != kind)
9212 PyMem_Free(buf2);
9213
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 onError:
9216 Py_DECREF(sub_obj);
9217 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 if (kind2 != kind && buf2)
9219 PyMem_Free(buf2);
9220 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009221}
9222
Alexander Belopolsky40018472011-02-26 01:02:56 +00009223Py_ssize_t
9224PyUnicode_Find(PyObject *str,
9225 PyObject *sub,
9226 Py_ssize_t start,
9227 Py_ssize_t end,
9228 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009229{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009230 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009231
Guido van Rossumd57fd912000-03-10 22:53:23 +00009232 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009233 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009234 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009235 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009236 if (!sub) {
9237 Py_DECREF(str);
9238 return -2;
9239 }
9240 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9241 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009242 Py_DECREF(str);
9243 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244 }
Tim Petersced69f82003-09-16 20:30:58 +00009245
Victor Stinner794d5672011-10-10 03:21:36 +02009246 result = any_find_slice(direction,
9247 str, sub, start, end
9248 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009249
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009251 Py_DECREF(sub);
9252
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253 return result;
9254}
9255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256Py_ssize_t
9257PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9258 Py_ssize_t start, Py_ssize_t end,
9259 int direction)
9260{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009261 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009262 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 if (PyUnicode_READY(str) == -1)
9264 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009265 if (start < 0 || end < 0) {
9266 PyErr_SetString(PyExc_IndexError, "string index out of range");
9267 return -2;
9268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009269 if (end > PyUnicode_GET_LENGTH(str))
9270 end = PyUnicode_GET_LENGTH(str);
9271 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009272 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9273 kind, end-start, ch, direction);
9274 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009276 else
9277 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278}
9279
Alexander Belopolsky40018472011-02-26 01:02:56 +00009280static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009281tailmatch(PyObject *self,
9282 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009283 Py_ssize_t start,
9284 Py_ssize_t end,
9285 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 int kind_self;
9288 int kind_sub;
9289 void *data_self;
9290 void *data_sub;
9291 Py_ssize_t offset;
9292 Py_ssize_t i;
9293 Py_ssize_t end_sub;
9294
9295 if (PyUnicode_READY(self) == -1 ||
9296 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009297 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298
9299 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 return 1;
9301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9303 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009304 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009305 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307 kind_self = PyUnicode_KIND(self);
9308 data_self = PyUnicode_DATA(self);
9309 kind_sub = PyUnicode_KIND(substring);
9310 data_sub = PyUnicode_DATA(substring);
9311 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9312
9313 if (direction > 0)
9314 offset = end;
9315 else
9316 offset = start;
9317
9318 if (PyUnicode_READ(kind_self, data_self, offset) ==
9319 PyUnicode_READ(kind_sub, data_sub, 0) &&
9320 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9321 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9322 /* If both are of the same kind, memcmp is sufficient */
9323 if (kind_self == kind_sub) {
9324 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009325 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 data_sub,
9327 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009328 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009329 }
9330 /* otherwise we have to compare each character by first accesing it */
9331 else {
9332 /* We do not need to compare 0 and len(substring)-1 because
9333 the if statement above ensured already that they are equal
9334 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 for (i = 1; i < end_sub; ++i) {
9336 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9337 PyUnicode_READ(kind_sub, data_sub, i))
9338 return 0;
9339 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009340 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342 }
9343
9344 return 0;
9345}
9346
Alexander Belopolsky40018472011-02-26 01:02:56 +00009347Py_ssize_t
9348PyUnicode_Tailmatch(PyObject *str,
9349 PyObject *substr,
9350 Py_ssize_t start,
9351 Py_ssize_t end,
9352 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009354 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009355
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356 str = PyUnicode_FromObject(str);
9357 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009358 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359 substr = PyUnicode_FromObject(substr);
9360 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009361 Py_DECREF(str);
9362 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363 }
Tim Petersced69f82003-09-16 20:30:58 +00009364
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009365 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009366 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367 Py_DECREF(str);
9368 Py_DECREF(substr);
9369 return result;
9370}
9371
Guido van Rossumd57fd912000-03-10 22:53:23 +00009372/* Apply fixfct filter to the Unicode object self and return a
9373 reference to the modified object */
9374
Alexander Belopolsky40018472011-02-26 01:02:56 +00009375static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009376fixup(PyObject *self,
9377 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009378{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 PyObject *u;
9380 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009381 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009383 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009386 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 /* fix functions return the new maximum character in a string,
9389 if the kind of the resulting unicode object does not change,
9390 everything is fine. Otherwise we need to change the string kind
9391 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009392 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009393
9394 if (maxchar_new == 0) {
9395 /* no changes */;
9396 if (PyUnicode_CheckExact(self)) {
9397 Py_DECREF(u);
9398 Py_INCREF(self);
9399 return self;
9400 }
9401 else
9402 return u;
9403 }
9404
Victor Stinnere6abb482012-05-02 01:15:40 +02009405 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406
Victor Stinnereaab6042011-12-11 22:22:39 +01009407 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009409
9410 /* In case the maximum character changed, we need to
9411 convert the string to the new category. */
9412 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9413 if (v == NULL) {
9414 Py_DECREF(u);
9415 return NULL;
9416 }
9417 if (maxchar_new > maxchar_old) {
9418 /* If the maxchar increased so that the kind changed, not all
9419 characters are representable anymore and we need to fix the
9420 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009421 _PyUnicode_FastCopyCharacters(v, 0,
9422 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009423 maxchar_old = fixfct(v);
9424 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 }
9426 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009427 _PyUnicode_FastCopyCharacters(v, 0,
9428 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009430 Py_DECREF(u);
9431 assert(_PyUnicode_CheckConsistency(v, 1));
9432 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433}
9434
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009435static PyObject *
9436ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009438 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9439 char *resdata, *data = PyUnicode_DATA(self);
9440 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009441
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009442 res = PyUnicode_New(len, 127);
9443 if (res == NULL)
9444 return NULL;
9445 resdata = PyUnicode_DATA(res);
9446 if (lower)
9447 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009448 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009449 _Py_bytes_upper(resdata, data, len);
9450 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451}
9452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009454handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009456 Py_ssize_t j;
9457 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009458 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009459 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009460
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009461 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9462
9463 where ! is a negation and \p{xxx} is a character with property xxx.
9464 */
9465 for (j = i - 1; j >= 0; j--) {
9466 c = PyUnicode_READ(kind, data, j);
9467 if (!_PyUnicode_IsCaseIgnorable(c))
9468 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009470 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9471 if (final_sigma) {
9472 for (j = i + 1; j < length; j++) {
9473 c = PyUnicode_READ(kind, data, j);
9474 if (!_PyUnicode_IsCaseIgnorable(c))
9475 break;
9476 }
9477 final_sigma = j == length || !_PyUnicode_IsCased(c);
9478 }
9479 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480}
9481
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009482static int
9483lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9484 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009486 /* Obscure special case. */
9487 if (c == 0x3A3) {
9488 mapped[0] = handle_capital_sigma(kind, data, length, i);
9489 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009491 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492}
9493
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009494static Py_ssize_t
9495do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009496{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009497 Py_ssize_t i, k = 0;
9498 int n_res, j;
9499 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009500
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009501 c = PyUnicode_READ(kind, data, 0);
9502 n_res = _PyUnicode_ToUpperFull(c, mapped);
9503 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009504 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009505 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009507 for (i = 1; i < length; i++) {
9508 c = PyUnicode_READ(kind, data, i);
9509 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9510 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009511 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009512 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009513 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009514 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009515 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516}
9517
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009518static Py_ssize_t
9519do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9520 Py_ssize_t i, k = 0;
9521
9522 for (i = 0; i < length; i++) {
9523 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9524 int n_res, j;
9525 if (Py_UNICODE_ISUPPER(c)) {
9526 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9527 }
9528 else if (Py_UNICODE_ISLOWER(c)) {
9529 n_res = _PyUnicode_ToUpperFull(c, mapped);
9530 }
9531 else {
9532 n_res = 1;
9533 mapped[0] = c;
9534 }
9535 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009536 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009537 res[k++] = mapped[j];
9538 }
9539 }
9540 return k;
9541}
9542
9543static Py_ssize_t
9544do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9545 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009547 Py_ssize_t i, k = 0;
9548
9549 for (i = 0; i < length; i++) {
9550 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9551 int n_res, j;
9552 if (lower)
9553 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9554 else
9555 n_res = _PyUnicode_ToUpperFull(c, mapped);
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(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9566{
9567 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9568}
9569
9570static Py_ssize_t
9571do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9572{
9573 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9574}
9575
Benjamin Petersone51757f2012-01-12 21:10:29 -05009576static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009577do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9578{
9579 Py_ssize_t i, k = 0;
9580
9581 for (i = 0; i < length; i++) {
9582 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9583 Py_UCS4 mapped[3];
9584 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9585 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009586 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009587 res[k++] = mapped[j];
9588 }
9589 }
9590 return k;
9591}
9592
9593static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009594do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9595{
9596 Py_ssize_t i, k = 0;
9597 int previous_is_cased;
9598
9599 previous_is_cased = 0;
9600 for (i = 0; i < length; i++) {
9601 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9602 Py_UCS4 mapped[3];
9603 int n_res, j;
9604
9605 if (previous_is_cased)
9606 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9607 else
9608 n_res = _PyUnicode_ToTitleFull(c, mapped);
9609
9610 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009611 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009612 res[k++] = mapped[j];
9613 }
9614
9615 previous_is_cased = _PyUnicode_IsCased(c);
9616 }
9617 return k;
9618}
9619
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009620static PyObject *
9621case_operation(PyObject *self,
9622 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9623{
9624 PyObject *res = NULL;
9625 Py_ssize_t length, newlength = 0;
9626 int kind, outkind;
9627 void *data, *outdata;
9628 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9629
Benjamin Petersoneea48462012-01-16 14:28:50 -05009630 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009631
9632 kind = PyUnicode_KIND(self);
9633 data = PyUnicode_DATA(self);
9634 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009635 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009636 PyErr_SetString(PyExc_OverflowError, "string is too long");
9637 return NULL;
9638 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009639 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009640 if (tmp == NULL)
9641 return PyErr_NoMemory();
9642 newlength = perform(kind, data, length, tmp, &maxchar);
9643 res = PyUnicode_New(newlength, maxchar);
9644 if (res == NULL)
9645 goto leave;
9646 tmpend = tmp + newlength;
9647 outdata = PyUnicode_DATA(res);
9648 outkind = PyUnicode_KIND(res);
9649 switch (outkind) {
9650 case PyUnicode_1BYTE_KIND:
9651 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9652 break;
9653 case PyUnicode_2BYTE_KIND:
9654 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9655 break;
9656 case PyUnicode_4BYTE_KIND:
9657 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9658 break;
9659 default:
9660 assert(0);
9661 break;
9662 }
9663 leave:
9664 PyMem_FREE(tmp);
9665 return res;
9666}
9667
Tim Peters8ce9f162004-08-27 01:49:32 +00009668PyObject *
9669PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009672 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009674 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009675 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9676 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009677 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009679 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009681 int use_memcpy;
9682 unsigned char *res_data = NULL, *sep_data = NULL;
9683 PyObject *last_obj;
9684 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009686 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009687 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009688 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009689 }
9690
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009691 /* NOTE: the following code can't call back into Python code,
9692 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009693 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009694
Tim Peters05eba1f2004-08-27 21:32:02 +00009695 seqlen = PySequence_Fast_GET_SIZE(fseq);
9696 /* If empty sequence, return u"". */
9697 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009698 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009699 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009700 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009701
Tim Peters05eba1f2004-08-27 21:32:02 +00009702 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009703 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009704 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009705 if (seqlen == 1) {
9706 if (PyUnicode_CheckExact(items[0])) {
9707 res = items[0];
9708 Py_INCREF(res);
9709 Py_DECREF(fseq);
9710 return res;
9711 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009712 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009713 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009714 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009715 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009716 /* Set up sep and seplen */
9717 if (separator == NULL) {
9718 /* fall back to a blank space separator */
9719 sep = PyUnicode_FromOrdinal(' ');
9720 if (!sep)
9721 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009722 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009723 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009724 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009725 else {
9726 if (!PyUnicode_Check(separator)) {
9727 PyErr_Format(PyExc_TypeError,
9728 "separator: expected str instance,"
9729 " %.80s found",
9730 Py_TYPE(separator)->tp_name);
9731 goto onError;
9732 }
9733 if (PyUnicode_READY(separator))
9734 goto onError;
9735 sep = separator;
9736 seplen = PyUnicode_GET_LENGTH(separator);
9737 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9738 /* inc refcount to keep this code path symmetric with the
9739 above case of a blank separator */
9740 Py_INCREF(sep);
9741 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009742 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009743 }
9744
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009745 /* There are at least two things to join, or else we have a subclass
9746 * of str in the sequence.
9747 * Do a pre-pass to figure out the total amount of space we'll
9748 * need (sz), and see whether all argument are strings.
9749 */
9750 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009751#ifdef Py_DEBUG
9752 use_memcpy = 0;
9753#else
9754 use_memcpy = 1;
9755#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009756 for (i = 0; i < seqlen; i++) {
9757 const Py_ssize_t old_sz = sz;
9758 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009759 if (!PyUnicode_Check(item)) {
9760 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009761 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009762 " %.80s found",
9763 i, Py_TYPE(item)->tp_name);
9764 goto onError;
9765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766 if (PyUnicode_READY(item) == -1)
9767 goto onError;
9768 sz += PyUnicode_GET_LENGTH(item);
9769 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009770 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009771 if (i != 0)
9772 sz += seplen;
9773 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9774 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009775 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009776 goto onError;
9777 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009778 if (use_memcpy && last_obj != NULL) {
9779 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9780 use_memcpy = 0;
9781 }
9782 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009783 }
Tim Petersced69f82003-09-16 20:30:58 +00009784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009786 if (res == NULL)
9787 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009788
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009789 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009790#ifdef Py_DEBUG
9791 use_memcpy = 0;
9792#else
9793 if (use_memcpy) {
9794 res_data = PyUnicode_1BYTE_DATA(res);
9795 kind = PyUnicode_KIND(res);
9796 if (seplen != 0)
9797 sep_data = PyUnicode_1BYTE_DATA(sep);
9798 }
9799#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009800 if (use_memcpy) {
9801 for (i = 0; i < seqlen; ++i) {
9802 Py_ssize_t itemlen;
9803 item = items[i];
9804
9805 /* Copy item, and maybe the separator. */
9806 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009807 Py_MEMCPY(res_data,
9808 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009809 kind * seplen);
9810 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009811 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009812
9813 itemlen = PyUnicode_GET_LENGTH(item);
9814 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009815 Py_MEMCPY(res_data,
9816 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009817 kind * itemlen);
9818 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009819 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009820 }
9821 assert(res_data == PyUnicode_1BYTE_DATA(res)
9822 + kind * PyUnicode_GET_LENGTH(res));
9823 }
9824 else {
9825 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9826 Py_ssize_t itemlen;
9827 item = items[i];
9828
9829 /* Copy item, and maybe the separator. */
9830 if (i && seplen != 0) {
9831 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9832 res_offset += seplen;
9833 }
9834
9835 itemlen = PyUnicode_GET_LENGTH(item);
9836 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009837 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009838 res_offset += itemlen;
9839 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009840 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009841 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009842 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009843
Tim Peters05eba1f2004-08-27 21:32:02 +00009844 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009846 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009848
Benjamin Peterson29060642009-01-31 22:14:21 +00009849 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009850 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009852 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009853 return NULL;
9854}
9855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009856#define FILL(kind, data, value, start, length) \
9857 do { \
9858 Py_ssize_t i_ = 0; \
9859 assert(kind != PyUnicode_WCHAR_KIND); \
9860 switch ((kind)) { \
9861 case PyUnicode_1BYTE_KIND: { \
9862 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009863 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009864 break; \
9865 } \
9866 case PyUnicode_2BYTE_KIND: { \
9867 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9868 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9869 break; \
9870 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009871 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9873 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9874 break; \
9875 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009876 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 } \
9878 } while (0)
9879
Victor Stinnerd3f08822012-05-29 12:57:52 +02009880void
9881_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9882 Py_UCS4 fill_char)
9883{
9884 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9885 const void *data = PyUnicode_DATA(unicode);
9886 assert(PyUnicode_IS_READY(unicode));
9887 assert(unicode_modifiable(unicode));
9888 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9889 assert(start >= 0);
9890 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9891 FILL(kind, data, fill_char, start, length);
9892}
9893
Victor Stinner3fe55312012-01-04 00:33:50 +01009894Py_ssize_t
9895PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9896 Py_UCS4 fill_char)
9897{
9898 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009899
9900 if (!PyUnicode_Check(unicode)) {
9901 PyErr_BadInternalCall();
9902 return -1;
9903 }
9904 if (PyUnicode_READY(unicode) == -1)
9905 return -1;
9906 if (unicode_check_modifiable(unicode))
9907 return -1;
9908
Victor Stinnerd3f08822012-05-29 12:57:52 +02009909 if (start < 0) {
9910 PyErr_SetString(PyExc_IndexError, "string index out of range");
9911 return -1;
9912 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009913 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9914 PyErr_SetString(PyExc_ValueError,
9915 "fill character is bigger than "
9916 "the string maximum character");
9917 return -1;
9918 }
9919
9920 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9921 length = Py_MIN(maxlen, length);
9922 if (length <= 0)
9923 return 0;
9924
Victor Stinnerd3f08822012-05-29 12:57:52 +02009925 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009926 return length;
9927}
9928
Victor Stinner9310abb2011-10-05 00:59:23 +02009929static PyObject *
9930pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009931 Py_ssize_t left,
9932 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 PyObject *u;
9936 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009937 int kind;
9938 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009939
9940 if (left < 0)
9941 left = 0;
9942 if (right < 0)
9943 right = 0;
9944
Victor Stinnerc4b49542011-12-11 22:44:26 +01009945 if (left == 0 && right == 0)
9946 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009948 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9949 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009950 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9951 return NULL;
9952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009954 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009955 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009956 if (!u)
9957 return NULL;
9958
9959 kind = PyUnicode_KIND(u);
9960 data = PyUnicode_DATA(u);
9961 if (left)
9962 FILL(kind, data, fill, 0, left);
9963 if (right)
9964 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009965 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009966 assert(_PyUnicode_CheckConsistency(u, 1));
9967 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009968}
9969
Alexander Belopolsky40018472011-02-26 01:02:56 +00009970PyObject *
9971PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009972{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009973 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974
9975 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009976 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009977 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009978 if (PyUnicode_READY(string) == -1) {
9979 Py_DECREF(string);
9980 return NULL;
9981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009982
Benjamin Petersonead6b532011-12-20 17:23:42 -06009983 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009985 if (PyUnicode_IS_ASCII(string))
9986 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009987 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009988 PyUnicode_GET_LENGTH(string), keepends);
9989 else
9990 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009991 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009992 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993 break;
9994 case PyUnicode_2BYTE_KIND:
9995 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009996 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 PyUnicode_GET_LENGTH(string), keepends);
9998 break;
9999 case PyUnicode_4BYTE_KIND:
10000 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010001 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 PyUnicode_GET_LENGTH(string), keepends);
10003 break;
10004 default:
10005 assert(0);
10006 list = 0;
10007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010008 Py_DECREF(string);
10009 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010010}
10011
Alexander Belopolsky40018472011-02-26 01:02:56 +000010012static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010013split(PyObject *self,
10014 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010015 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 int kind1, kind2, kind;
10018 void *buf1, *buf2;
10019 Py_ssize_t len1, len2;
10020 PyObject* out;
10021
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010023 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 if (PyUnicode_READY(self) == -1)
10026 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010029 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010030 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010031 if (PyUnicode_IS_ASCII(self))
10032 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010033 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010034 PyUnicode_GET_LENGTH(self), maxcount
10035 );
10036 else
10037 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010038 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010039 PyUnicode_GET_LENGTH(self), maxcount
10040 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 case PyUnicode_2BYTE_KIND:
10042 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010043 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 PyUnicode_GET_LENGTH(self), maxcount
10045 );
10046 case PyUnicode_4BYTE_KIND:
10047 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010048 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 PyUnicode_GET_LENGTH(self), maxcount
10050 );
10051 default:
10052 assert(0);
10053 return NULL;
10054 }
10055
10056 if (PyUnicode_READY(substring) == -1)
10057 return NULL;
10058
10059 kind1 = PyUnicode_KIND(self);
10060 kind2 = PyUnicode_KIND(substring);
10061 kind = kind1 > kind2 ? kind1 : kind2;
10062 buf1 = PyUnicode_DATA(self);
10063 buf2 = PyUnicode_DATA(substring);
10064 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010065 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 if (!buf1)
10067 return NULL;
10068 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010069 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 if (!buf2) {
10071 if (kind1 != kind) PyMem_Free(buf1);
10072 return NULL;
10073 }
10074 len1 = PyUnicode_GET_LENGTH(self);
10075 len2 = PyUnicode_GET_LENGTH(substring);
10076
Benjamin Petersonead6b532011-12-20 17:23:42 -060010077 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010079 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10080 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010081 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010082 else
10083 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010084 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 break;
10086 case PyUnicode_2BYTE_KIND:
10087 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 break;
10090 case PyUnicode_4BYTE_KIND:
10091 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010092 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 break;
10094 default:
10095 out = NULL;
10096 }
10097 if (kind1 != kind)
10098 PyMem_Free(buf1);
10099 if (kind2 != kind)
10100 PyMem_Free(buf2);
10101 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010102}
10103
Alexander Belopolsky40018472011-02-26 01:02:56 +000010104static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010105rsplit(PyObject *self,
10106 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010107 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010108{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 int kind1, kind2, kind;
10110 void *buf1, *buf2;
10111 Py_ssize_t len1, len2;
10112 PyObject* out;
10113
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010114 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010115 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 if (PyUnicode_READY(self) == -1)
10118 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010120 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010121 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010123 if (PyUnicode_IS_ASCII(self))
10124 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010125 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126 PyUnicode_GET_LENGTH(self), maxcount
10127 );
10128 else
10129 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010130 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010131 PyUnicode_GET_LENGTH(self), maxcount
10132 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 case PyUnicode_2BYTE_KIND:
10134 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010135 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 PyUnicode_GET_LENGTH(self), maxcount
10137 );
10138 case PyUnicode_4BYTE_KIND:
10139 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010140 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 PyUnicode_GET_LENGTH(self), maxcount
10142 );
10143 default:
10144 assert(0);
10145 return NULL;
10146 }
10147
10148 if (PyUnicode_READY(substring) == -1)
10149 return NULL;
10150
10151 kind1 = PyUnicode_KIND(self);
10152 kind2 = PyUnicode_KIND(substring);
10153 kind = kind1 > kind2 ? kind1 : kind2;
10154 buf1 = PyUnicode_DATA(self);
10155 buf2 = PyUnicode_DATA(substring);
10156 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 if (!buf1)
10159 return NULL;
10160 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010161 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 if (!buf2) {
10163 if (kind1 != kind) PyMem_Free(buf1);
10164 return NULL;
10165 }
10166 len1 = PyUnicode_GET_LENGTH(self);
10167 len2 = PyUnicode_GET_LENGTH(substring);
10168
Benjamin Petersonead6b532011-12-20 17:23:42 -060010169 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010171 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10172 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010173 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 else
10175 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 break;
10178 case PyUnicode_2BYTE_KIND:
10179 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010180 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 break;
10182 case PyUnicode_4BYTE_KIND:
10183 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010184 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 break;
10186 default:
10187 out = NULL;
10188 }
10189 if (kind1 != kind)
10190 PyMem_Free(buf1);
10191 if (kind2 != kind)
10192 PyMem_Free(buf2);
10193 return out;
10194}
10195
10196static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010197anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10198 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010200 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010202 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10203 return asciilib_find(buf1, len1, buf2, len2, offset);
10204 else
10205 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 case PyUnicode_2BYTE_KIND:
10207 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10208 case PyUnicode_4BYTE_KIND:
10209 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10210 }
10211 assert(0);
10212 return -1;
10213}
10214
10215static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010216anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10217 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010219 switch (kind) {
10220 case PyUnicode_1BYTE_KIND:
10221 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10222 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10223 else
10224 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10225 case PyUnicode_2BYTE_KIND:
10226 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10227 case PyUnicode_4BYTE_KIND:
10228 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10229 }
10230 assert(0);
10231 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010232}
10233
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010234static void
10235replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10236 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10237{
10238 int kind = PyUnicode_KIND(u);
10239 void *data = PyUnicode_DATA(u);
10240 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10241 if (kind == PyUnicode_1BYTE_KIND) {
10242 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10243 (Py_UCS1 *)data + len,
10244 u1, u2, maxcount);
10245 }
10246 else if (kind == PyUnicode_2BYTE_KIND) {
10247 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10248 (Py_UCS2 *)data + len,
10249 u1, u2, maxcount);
10250 }
10251 else {
10252 assert(kind == PyUnicode_4BYTE_KIND);
10253 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10254 (Py_UCS4 *)data + len,
10255 u1, u2, maxcount);
10256 }
10257}
10258
Alexander Belopolsky40018472011-02-26 01:02:56 +000010259static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260replace(PyObject *self, PyObject *str1,
10261 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010262{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 PyObject *u;
10264 char *sbuf = PyUnicode_DATA(self);
10265 char *buf1 = PyUnicode_DATA(str1);
10266 char *buf2 = PyUnicode_DATA(str2);
10267 int srelease = 0, release1 = 0, release2 = 0;
10268 int skind = PyUnicode_KIND(self);
10269 int kind1 = PyUnicode_KIND(str1);
10270 int kind2 = PyUnicode_KIND(str2);
10271 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10272 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10273 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010274 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010275 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010276
10277 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010278 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010280 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281
Victor Stinner59de0ee2011-10-07 10:01:28 +020010282 if (str1 == str2)
10283 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284
Victor Stinner49a0a212011-10-12 23:46:10 +020010285 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010286 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10287 if (maxchar < maxchar_str1)
10288 /* substring too wide to be present */
10289 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010290 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10291 /* Replacing str1 with str2 may cause a maxchar reduction in the
10292 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010293 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010294 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010297 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010299 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010301 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010303 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010304
Victor Stinner69ed0f42013-04-09 21:48:24 +020010305 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010306 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010307 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010308 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010309 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010310 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010311 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010313
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010314 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10315 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010316 }
10317 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 int rkind = skind;
10319 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010320 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 if (kind1 < rkind) {
10323 /* widen substring */
10324 buf1 = _PyUnicode_AsKind(str1, rkind);
10325 if (!buf1) goto error;
10326 release1 = 1;
10327 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010328 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 if (i < 0)
10330 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 if (rkind > kind2) {
10332 /* widen replacement */
10333 buf2 = _PyUnicode_AsKind(str2, rkind);
10334 if (!buf2) goto error;
10335 release2 = 1;
10336 }
10337 else if (rkind < kind2) {
10338 /* widen self and buf1 */
10339 rkind = kind2;
10340 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010341 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 sbuf = _PyUnicode_AsKind(self, rkind);
10343 if (!sbuf) goto error;
10344 srelease = 1;
10345 buf1 = _PyUnicode_AsKind(str1, rkind);
10346 if (!buf1) goto error;
10347 release1 = 1;
10348 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010349 u = PyUnicode_New(slen, maxchar);
10350 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010352 assert(PyUnicode_KIND(u) == rkind);
10353 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010354
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010355 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010356 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010357 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010359 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010361
10362 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010363 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010364 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010365 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010366 if (i == -1)
10367 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010368 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010370 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010372 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010374 }
10375 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010377 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 int rkind = skind;
10379 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010382 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 buf1 = _PyUnicode_AsKind(str1, rkind);
10384 if (!buf1) goto error;
10385 release1 = 1;
10386 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010387 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010388 if (n == 0)
10389 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010391 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 buf2 = _PyUnicode_AsKind(str2, rkind);
10393 if (!buf2) goto error;
10394 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010397 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 rkind = kind2;
10399 sbuf = _PyUnicode_AsKind(self, rkind);
10400 if (!sbuf) goto error;
10401 srelease = 1;
10402 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010403 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 buf1 = _PyUnicode_AsKind(str1, rkind);
10405 if (!buf1) goto error;
10406 release1 = 1;
10407 }
10408 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10409 PyUnicode_GET_LENGTH(str1))); */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010410 if (len2 > len1 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 PyErr_SetString(PyExc_OverflowError,
10412 "replace string is too long");
10413 goto error;
10414 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010415 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010417 _Py_INCREF_UNICODE_EMPTY();
10418 if (!unicode_empty)
10419 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010420 u = unicode_empty;
10421 goto done;
10422 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010423 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 PyErr_SetString(PyExc_OverflowError,
10425 "replace string is too long");
10426 goto error;
10427 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010428 u = PyUnicode_New(new_size, maxchar);
10429 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010431 assert(PyUnicode_KIND(u) == rkind);
10432 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 ires = i = 0;
10434 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 while (n-- > 0) {
10436 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010437 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010438 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010439 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010440 if (j == -1)
10441 break;
10442 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010443 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010444 memcpy(res + rkind * ires,
10445 sbuf + rkind * i,
10446 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010448 }
10449 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010451 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010453 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010455 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010459 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010460 memcpy(res + rkind * ires,
10461 sbuf + rkind * i,
10462 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010463 }
10464 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010465 /* interleave */
10466 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010467 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010469 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010471 if (--n <= 0)
10472 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010473 memcpy(res + rkind * ires,
10474 sbuf + rkind * i,
10475 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 ires++;
10477 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010478 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010479 memcpy(res + rkind * ires,
10480 sbuf + rkind * i,
10481 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010482 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010483 }
10484
10485 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010486 unicode_adjust_maxchar(&u);
10487 if (u == NULL)
10488 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010489 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010490
10491 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 if (srelease)
10493 PyMem_FREE(sbuf);
10494 if (release1)
10495 PyMem_FREE(buf1);
10496 if (release2)
10497 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010498 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500
Benjamin Peterson29060642009-01-31 22:14:21 +000010501 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010502 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (srelease)
10504 PyMem_FREE(sbuf);
10505 if (release1)
10506 PyMem_FREE(buf1);
10507 if (release2)
10508 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010509 return unicode_result_unchanged(self);
10510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 error:
10512 if (srelease && sbuf)
10513 PyMem_FREE(sbuf);
10514 if (release1 && buf1)
10515 PyMem_FREE(buf1);
10516 if (release2 && buf2)
10517 PyMem_FREE(buf2);
10518 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010519}
10520
10521/* --- Unicode Object Methods --------------------------------------------- */
10522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010523PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010524 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010525\n\
10526Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010527characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528
10529static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010530unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010531{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010532 if (PyUnicode_READY(self) == -1)
10533 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010534 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535}
10536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010537PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010538 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010539\n\
10540Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010541have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542
10543static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010544unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010546 if (PyUnicode_READY(self) == -1)
10547 return NULL;
10548 if (PyUnicode_GET_LENGTH(self) == 0)
10549 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010550 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010551}
10552
Benjamin Petersond5890c82012-01-14 13:23:30 -050010553PyDoc_STRVAR(casefold__doc__,
10554 "S.casefold() -> str\n\
10555\n\
10556Return a version of S suitable for caseless comparisons.");
10557
10558static PyObject *
10559unicode_casefold(PyObject *self)
10560{
10561 if (PyUnicode_READY(self) == -1)
10562 return NULL;
10563 if (PyUnicode_IS_ASCII(self))
10564 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010565 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010566}
10567
10568
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010569/* Argument converter. Coerces to a single unicode character */
10570
10571static int
10572convert_uc(PyObject *obj, void *addr)
10573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010576
Benjamin Peterson14339b62009-01-31 16:36:08 +000010577 uniobj = PyUnicode_FromObject(obj);
10578 if (uniobj == NULL) {
10579 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010581 return 0;
10582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010584 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010585 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010586 Py_DECREF(uniobj);
10587 return 0;
10588 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010590 Py_DECREF(uniobj);
10591 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010592}
10593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010594PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010595 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010597Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010598done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010599
10600static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010601unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010603 Py_ssize_t marg, left;
10604 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 Py_UCS4 fillchar = ' ';
10606
Victor Stinnere9a29352011-10-01 02:14:59 +020010607 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010609
Benjamin Petersonbac79492012-01-14 13:34:47 -050010610 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010611 return NULL;
10612
Victor Stinnerc4b49542011-12-11 22:44:26 +010010613 if (PyUnicode_GET_LENGTH(self) >= width)
10614 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615
Victor Stinnerc4b49542011-12-11 22:44:26 +010010616 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010617 left = marg / 2 + (marg & width & 1);
10618
Victor Stinner9310abb2011-10-05 00:59:23 +020010619 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620}
10621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622/* This function assumes that str1 and str2 are readied by the caller. */
10623
Marc-André Lemburge5034372000-08-08 08:04:29 +000010624static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010625unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010626{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010627#define COMPARE(TYPE1, TYPE2) \
10628 do { \
10629 TYPE1* p1 = (TYPE1 *)data1; \
10630 TYPE2* p2 = (TYPE2 *)data2; \
10631 TYPE1* end = p1 + len; \
10632 Py_UCS4 c1, c2; \
10633 for (; p1 != end; p1++, p2++) { \
10634 c1 = *p1; \
10635 c2 = *p2; \
10636 if (c1 != c2) \
10637 return (c1 < c2) ? -1 : 1; \
10638 } \
10639 } \
10640 while (0)
10641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642 int kind1, kind2;
10643 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010644 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 kind1 = PyUnicode_KIND(str1);
10647 kind2 = PyUnicode_KIND(str2);
10648 data1 = PyUnicode_DATA(str1);
10649 data2 = PyUnicode_DATA(str2);
10650 len1 = PyUnicode_GET_LENGTH(str1);
10651 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010652 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010653
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010654 switch(kind1) {
10655 case PyUnicode_1BYTE_KIND:
10656 {
10657 switch(kind2) {
10658 case PyUnicode_1BYTE_KIND:
10659 {
10660 int cmp = memcmp(data1, data2, len);
10661 /* normalize result of memcmp() into the range [-1; 1] */
10662 if (cmp < 0)
10663 return -1;
10664 if (cmp > 0)
10665 return 1;
10666 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010667 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010668 case PyUnicode_2BYTE_KIND:
10669 COMPARE(Py_UCS1, Py_UCS2);
10670 break;
10671 case PyUnicode_4BYTE_KIND:
10672 COMPARE(Py_UCS1, Py_UCS4);
10673 break;
10674 default:
10675 assert(0);
10676 }
10677 break;
10678 }
10679 case PyUnicode_2BYTE_KIND:
10680 {
10681 switch(kind2) {
10682 case PyUnicode_1BYTE_KIND:
10683 COMPARE(Py_UCS2, Py_UCS1);
10684 break;
10685 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010686 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010687 COMPARE(Py_UCS2, Py_UCS2);
10688 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010689 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010690 case PyUnicode_4BYTE_KIND:
10691 COMPARE(Py_UCS2, Py_UCS4);
10692 break;
10693 default:
10694 assert(0);
10695 }
10696 break;
10697 }
10698 case PyUnicode_4BYTE_KIND:
10699 {
10700 switch(kind2) {
10701 case PyUnicode_1BYTE_KIND:
10702 COMPARE(Py_UCS4, Py_UCS1);
10703 break;
10704 case PyUnicode_2BYTE_KIND:
10705 COMPARE(Py_UCS4, Py_UCS2);
10706 break;
10707 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010708 {
10709#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10710 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10711 /* normalize result of wmemcmp() into the range [-1; 1] */
10712 if (cmp < 0)
10713 return -1;
10714 if (cmp > 0)
10715 return 1;
10716#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010717 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010718#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010719 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010720 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010721 default:
10722 assert(0);
10723 }
10724 break;
10725 }
10726 default:
10727 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010728 }
10729
Victor Stinner770e19e2012-10-04 22:59:45 +020010730 if (len1 == len2)
10731 return 0;
10732 if (len1 < len2)
10733 return -1;
10734 else
10735 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010736
10737#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010738}
10739
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010740Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010741unicode_compare_eq(PyObject *str1, PyObject *str2)
10742{
10743 int kind;
10744 void *data1, *data2;
10745 Py_ssize_t len;
10746 int cmp;
10747
Victor Stinnere5567ad2012-10-23 02:48:49 +020010748 len = PyUnicode_GET_LENGTH(str1);
10749 if (PyUnicode_GET_LENGTH(str2) != len)
10750 return 0;
10751 kind = PyUnicode_KIND(str1);
10752 if (PyUnicode_KIND(str2) != kind)
10753 return 0;
10754 data1 = PyUnicode_DATA(str1);
10755 data2 = PyUnicode_DATA(str2);
10756
10757 cmp = memcmp(data1, data2, len * kind);
10758 return (cmp == 0);
10759}
10760
10761
Alexander Belopolsky40018472011-02-26 01:02:56 +000010762int
10763PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10766 if (PyUnicode_READY(left) == -1 ||
10767 PyUnicode_READY(right) == -1)
10768 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010769
10770 /* a string is equal to itself */
10771 if (left == right)
10772 return 0;
10773
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010774 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010776 PyErr_Format(PyExc_TypeError,
10777 "Can't compare %.100s and %.100s",
10778 left->ob_type->tp_name,
10779 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010780 return -1;
10781}
10782
Martin v. Löwis5b222132007-06-10 09:51:05 +000010783int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010784_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10785{
10786 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10787 if (right_str == NULL)
10788 return -1;
10789 return PyUnicode_Compare(left, right_str);
10790}
10791
10792int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010793PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10794{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 Py_ssize_t i;
10796 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 Py_UCS4 chr;
10798
Victor Stinner910337b2011-10-03 03:20:16 +020010799 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010800 if (PyUnicode_READY(uni) == -1)
10801 return -1;
10802 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010803 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010804 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010805 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010806 size_t len, len2 = strlen(str);
10807 int cmp;
10808
10809 len = Py_MIN(len1, len2);
10810 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010811 if (cmp != 0) {
10812 if (cmp < 0)
10813 return -1;
10814 else
10815 return 1;
10816 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010817 if (len1 > len2)
10818 return 1; /* uni is longer */
10819 if (len2 > len1)
10820 return -1; /* str is longer */
10821 return 0;
10822 }
10823 else {
10824 void *data = PyUnicode_DATA(uni);
10825 /* Compare Unicode string and source character set string */
10826 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010827 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010828 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10829 /* This check keeps Python strings that end in '\0' from comparing equal
10830 to C strings identical up to that point. */
10831 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10832 return 1; /* uni is longer */
10833 if (str[i])
10834 return -1; /* str is longer */
10835 return 0;
10836 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010837}
10838
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010839
Benjamin Peterson29060642009-01-31 22:14:21 +000010840#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010841 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010842
Alexander Belopolsky40018472011-02-26 01:02:56 +000010843PyObject *
10844PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010845{
10846 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010847 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010848
Victor Stinnere5567ad2012-10-23 02:48:49 +020010849 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10850 Py_RETURN_NOTIMPLEMENTED;
10851
10852 if (PyUnicode_READY(left) == -1 ||
10853 PyUnicode_READY(right) == -1)
10854 return NULL;
10855
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010856 if (left == right) {
10857 switch (op) {
10858 case Py_EQ:
10859 case Py_LE:
10860 case Py_GE:
10861 /* a string is equal to itself */
10862 v = Py_True;
10863 break;
10864 case Py_NE:
10865 case Py_LT:
10866 case Py_GT:
10867 v = Py_False;
10868 break;
10869 default:
10870 PyErr_BadArgument();
10871 return NULL;
10872 }
10873 }
10874 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010875 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010876 result ^= (op == Py_NE);
10877 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010878 }
10879 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010880 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010881
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010882 /* Convert the return value to a Boolean */
10883 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010884 case Py_LE:
10885 v = TEST_COND(result <= 0);
10886 break;
10887 case Py_GE:
10888 v = TEST_COND(result >= 0);
10889 break;
10890 case Py_LT:
10891 v = TEST_COND(result == -1);
10892 break;
10893 case Py_GT:
10894 v = TEST_COND(result == 1);
10895 break;
10896 default:
10897 PyErr_BadArgument();
10898 return NULL;
10899 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010900 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010901 Py_INCREF(v);
10902 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010903}
10904
Alexander Belopolsky40018472011-02-26 01:02:56 +000010905int
10906PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010907{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010908 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010909 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010910 void *buf1, *buf2;
10911 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010912 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010913
10914 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010915 sub = PyUnicode_FromObject(element);
10916 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010917 PyErr_Format(PyExc_TypeError,
10918 "'in <string>' requires string as left operand, not %s",
10919 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010920 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010921 }
10922
Thomas Wouters477c8d52006-05-27 19:21:47 +000010923 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010924 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010925 Py_DECREF(sub);
10926 return -1;
10927 }
10928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010929 kind1 = PyUnicode_KIND(str);
10930 kind2 = PyUnicode_KIND(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 buf1 = PyUnicode_DATA(str);
10932 buf2 = PyUnicode_DATA(sub);
Victor Stinner77282cb2013-04-14 19:22:47 +020010933 if (kind2 != kind1) {
10934 if (kind2 > kind1) {
Antoine Pitrou758153b2012-05-12 15:51:51 +020010935 Py_DECREF(sub);
10936 Py_DECREF(str);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010937 return 0;
Antoine Pitrou758153b2012-05-12 15:51:51 +020010938 }
Victor Stinner77282cb2013-04-14 19:22:47 +020010939 buf2 = _PyUnicode_AsKind(sub, kind1);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010940 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010941 if (!buf2) {
10942 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010943 Py_DECREF(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 return -1;
10945 }
10946 len1 = PyUnicode_GET_LENGTH(str);
10947 len2 = PyUnicode_GET_LENGTH(sub);
10948
Victor Stinner77282cb2013-04-14 19:22:47 +020010949 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010950 case PyUnicode_1BYTE_KIND:
10951 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10952 break;
10953 case PyUnicode_2BYTE_KIND:
10954 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10955 break;
10956 case PyUnicode_4BYTE_KIND:
10957 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10958 break;
10959 default:
10960 result = -1;
10961 assert(0);
10962 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010963
10964 Py_DECREF(str);
10965 Py_DECREF(sub);
10966
Victor Stinner77282cb2013-04-14 19:22:47 +020010967 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 PyMem_Free(buf2);
10969
Guido van Rossum403d68b2000-03-13 15:55:09 +000010970 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010971}
10972
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973/* Concat to string or Unicode object giving a new Unicode object. */
10974
Alexander Belopolsky40018472011-02-26 01:02:56 +000010975PyObject *
10976PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010979 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010980 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981
10982 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010988 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989
10990 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010991 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010992 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010994 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010995 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010997 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998 }
10999
Victor Stinner488fa492011-12-12 00:01:39 +010011000 u_len = PyUnicode_GET_LENGTH(u);
11001 v_len = PyUnicode_GET_LENGTH(v);
11002 if (u_len > PY_SSIZE_T_MAX - v_len) {
11003 PyErr_SetString(PyExc_OverflowError,
11004 "strings are too large to concat");
11005 goto onError;
11006 }
11007 new_len = u_len + v_len;
11008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011010 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011011 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011014 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011016 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011017 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11018 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 Py_DECREF(u);
11020 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011021 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023
Benjamin Peterson29060642009-01-31 22:14:21 +000011024 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025 Py_XDECREF(u);
11026 Py_XDECREF(v);
11027 return NULL;
11028}
11029
Walter Dörwald1ab83302007-05-18 17:15:44 +000011030void
Victor Stinner23e56682011-10-03 03:54:37 +020011031PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011032{
Victor Stinner23e56682011-10-03 03:54:37 +020011033 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011034 Py_UCS4 maxchar, maxchar2;
11035 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011036
11037 if (p_left == NULL) {
11038 if (!PyErr_Occurred())
11039 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011040 return;
11041 }
Victor Stinner23e56682011-10-03 03:54:37 +020011042 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011043 if (right == NULL || left == NULL
11044 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011045 if (!PyErr_Occurred())
11046 PyErr_BadInternalCall();
11047 goto error;
11048 }
11049
Benjamin Petersonbac79492012-01-14 13:34:47 -050011050 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011051 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011052 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011053 goto error;
11054
Victor Stinner488fa492011-12-12 00:01:39 +010011055 /* Shortcuts */
11056 if (left == unicode_empty) {
11057 Py_DECREF(left);
11058 Py_INCREF(right);
11059 *p_left = right;
11060 return;
11061 }
11062 if (right == unicode_empty)
11063 return;
11064
11065 left_len = PyUnicode_GET_LENGTH(left);
11066 right_len = PyUnicode_GET_LENGTH(right);
11067 if (left_len > PY_SSIZE_T_MAX - right_len) {
11068 PyErr_SetString(PyExc_OverflowError,
11069 "strings are too large to concat");
11070 goto error;
11071 }
11072 new_len = left_len + right_len;
11073
11074 if (unicode_modifiable(left)
11075 && PyUnicode_CheckExact(right)
11076 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011077 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11078 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011079 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011080 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011081 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11082 {
11083 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011084 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011085 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011086
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011087 /* copy 'right' into the newly allocated area of 'left' */
11088 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011089 }
Victor Stinner488fa492011-12-12 00:01:39 +010011090 else {
11091 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11092 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011093 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011094
Victor Stinner488fa492011-12-12 00:01:39 +010011095 /* Concat the two Unicode strings */
11096 res = PyUnicode_New(new_len, maxchar);
11097 if (res == NULL)
11098 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011099 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11100 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011101 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011102 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011103 }
11104 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011105 return;
11106
11107error:
Victor Stinner488fa492011-12-12 00:01:39 +010011108 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011109}
11110
11111void
11112PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11113{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011114 PyUnicode_Append(pleft, right);
11115 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011116}
11117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011118PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011119 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011121Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011122string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011123interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124
11125static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011126unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011128 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011129 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011130 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011132 int kind1, kind2, kind;
11133 void *buf1, *buf2;
11134 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135
Jesus Ceaac451502011-04-20 17:09:23 +020011136 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11137 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011138 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 kind1 = PyUnicode_KIND(self);
11141 kind2 = PyUnicode_KIND(substring);
Christian Heimesd47802e2013-06-29 21:33:36 +020011142 if (kind2 > kind1) {
11143 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011144 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011145 }
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011146 kind = kind1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 buf1 = PyUnicode_DATA(self);
11148 buf2 = PyUnicode_DATA(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011150 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 if (!buf2) {
11152 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153 return NULL;
11154 }
11155 len1 = PyUnicode_GET_LENGTH(self);
11156 len2 = PyUnicode_GET_LENGTH(substring);
11157
11158 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011159 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 case PyUnicode_1BYTE_KIND:
11161 iresult = ucs1lib_count(
11162 ((Py_UCS1*)buf1) + start, end - start,
11163 buf2, len2, PY_SSIZE_T_MAX
11164 );
11165 break;
11166 case PyUnicode_2BYTE_KIND:
11167 iresult = ucs2lib_count(
11168 ((Py_UCS2*)buf1) + start, end - start,
11169 buf2, len2, PY_SSIZE_T_MAX
11170 );
11171 break;
11172 case PyUnicode_4BYTE_KIND:
11173 iresult = ucs4lib_count(
11174 ((Py_UCS4*)buf1) + start, end - start,
11175 buf2, len2, PY_SSIZE_T_MAX
11176 );
11177 break;
11178 default:
11179 assert(0); iresult = 0;
11180 }
11181
11182 result = PyLong_FromSsize_t(iresult);
11183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 if (kind2 != kind)
11185 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186
11187 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011188
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 return result;
11190}
11191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011192PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011193 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011195Encode S using the codec registered for encoding. Default encoding\n\
11196is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011197handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011198a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11199'xmlcharrefreplace' as well as any other name registered with\n\
11200codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
11202static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011203unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011205 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 char *encoding = NULL;
11207 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011208
Benjamin Peterson308d6372009-09-18 21:42:35 +000011209 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11210 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011212 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011213}
11214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011215PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011216 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217\n\
11218Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011219If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220
11221static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011222unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011224 Py_ssize_t i, j, line_pos, src_len, incr;
11225 Py_UCS4 ch;
11226 PyObject *u;
11227 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011228 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011230 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011231 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232
Ezio Melotti745d54d2013-11-16 19:10:57 +020011233 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11234 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011235 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236
Antoine Pitrou22425222011-10-04 19:10:51 +020011237 if (PyUnicode_READY(self) == -1)
11238 return NULL;
11239
Thomas Wouters7e474022000-07-16 12:04:32 +000011240 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011241 src_len = PyUnicode_GET_LENGTH(self);
11242 i = j = line_pos = 0;
11243 kind = PyUnicode_KIND(self);
11244 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011245 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011246 for (; i < src_len; i++) {
11247 ch = PyUnicode_READ(kind, src_data, i);
11248 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011249 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011250 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011251 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011252 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011253 goto overflow;
11254 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011256 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011257 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011260 goto overflow;
11261 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 if (ch == '\n' || ch == '\r')
11264 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011266 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011267 if (!found)
11268 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011269
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011271 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272 if (!u)
11273 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011274 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275
Antoine Pitroue71d5742011-10-04 15:55:09 +020011276 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
Antoine Pitroue71d5742011-10-04 15:55:09 +020011278 for (; i < src_len; i++) {
11279 ch = PyUnicode_READ(kind, src_data, i);
11280 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011281 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011282 incr = tabsize - (line_pos % tabsize);
11283 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011284 FILL(kind, dest_data, ' ', j, incr);
11285 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011286 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011287 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011288 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011289 line_pos++;
11290 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011291 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 if (ch == '\n' || ch == '\r')
11293 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 }
11296 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011297 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011298
Antoine Pitroue71d5742011-10-04 15:55:09 +020011299 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011300 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11301 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302}
11303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011304PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011305 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306\n\
11307Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011308such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309arguments start and end are interpreted as in slice notation.\n\
11310\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011311Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312
11313static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011316 /* initialize variables to prevent gcc warning */
11317 PyObject *substring = NULL;
11318 Py_ssize_t start = 0;
11319 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011320 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321
Jesus Ceaac451502011-04-20 17:09:23 +020011322 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11323 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325
Christian Heimesd47802e2013-06-29 21:33:36 +020011326 if (PyUnicode_READY(self) == -1) {
11327 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011329 }
11330 if (PyUnicode_READY(substring) == -1) {
11331 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334
Victor Stinner7931d9a2011-11-04 00:22:48 +010011335 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336
11337 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011339 if (result == -2)
11340 return NULL;
11341
Christian Heimes217cfd12007-12-02 14:31:20 +000011342 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343}
11344
11345static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011346unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011348 void *data;
11349 enum PyUnicode_Kind kind;
11350 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011351
11352 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11353 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011355 }
11356 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11357 PyErr_SetString(PyExc_IndexError, "string index out of range");
11358 return NULL;
11359 }
11360 kind = PyUnicode_KIND(self);
11361 data = PyUnicode_DATA(self);
11362 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011363 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364}
11365
Guido van Rossumc2504932007-09-18 19:42:40 +000011366/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011367 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011368static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011369unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370{
Guido van Rossumc2504932007-09-18 19:42:40 +000011371 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011372 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011373
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011374#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011375 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011377 if (_PyUnicode_HASH(self) != -1)
11378 return _PyUnicode_HASH(self);
11379 if (PyUnicode_READY(self) == -1)
11380 return -1;
11381 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011382 /*
11383 We make the hash of the empty string be 0, rather than using
11384 (prefix ^ suffix), since this slightly obfuscates the hash secret
11385 */
11386 if (len == 0) {
11387 _PyUnicode_HASH(self) = 0;
11388 return 0;
11389 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011390 x = _Py_HashBytes(PyUnicode_DATA(self),
11391 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011393 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394}
11395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011396PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011399Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
11401static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011404 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011405 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011406 PyObject *substring = NULL;
11407 Py_ssize_t start = 0;
11408 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409
Jesus Ceaac451502011-04-20 17:09:23 +020011410 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11411 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413
Christian Heimesd47a0452013-06-29 21:21:37 +020011414 if (PyUnicode_READY(self) == -1) {
11415 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011417 }
11418 if (PyUnicode_READY(substring) == -1) {
11419 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011421 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422
Victor Stinner7931d9a2011-11-04 00:22:48 +010011423 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424
11425 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (result == -2)
11428 return NULL;
11429
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430 if (result < 0) {
11431 PyErr_SetString(PyExc_ValueError, "substring not found");
11432 return NULL;
11433 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011434
Christian Heimes217cfd12007-12-02 14:31:20 +000011435 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436}
11437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011438PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011441Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011442at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
11444static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011445unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 Py_ssize_t i, length;
11448 int kind;
11449 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 int cased;
11451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 if (PyUnicode_READY(self) == -1)
11453 return NULL;
11454 length = PyUnicode_GET_LENGTH(self);
11455 kind = PyUnicode_KIND(self);
11456 data = PyUnicode_DATA(self);
11457
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011459 if (length == 1)
11460 return PyBool_FromLong(
11461 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011463 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011465 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011466
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 for (i = 0; i < length; i++) {
11469 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011470
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11472 return PyBool_FromLong(0);
11473 else if (!cased && Py_UNICODE_ISLOWER(ch))
11474 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011476 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477}
11478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011479PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011482Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011483at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484
11485static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011486unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 Py_ssize_t i, length;
11489 int kind;
11490 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 int cased;
11492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 length = PyUnicode_GET_LENGTH(self);
11496 kind = PyUnicode_KIND(self);
11497 data = PyUnicode_DATA(self);
11498
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (length == 1)
11501 return PyBool_FromLong(
11502 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011504 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011507
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 for (i = 0; i < length; i++) {
11510 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011511
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11513 return PyBool_FromLong(0);
11514 else if (!cased && Py_UNICODE_ISUPPER(ch))
11515 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011517 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518}
11519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011520PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011521 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011523Return True if S is a titlecased string and there is at least one\n\
11524character in S, i.e. upper- and titlecase characters may only\n\
11525follow uncased characters and lowercase characters only cased ones.\n\
11526Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
11528static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011529unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 Py_ssize_t i, length;
11532 int kind;
11533 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534 int cased, previous_is_cased;
11535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011536 if (PyUnicode_READY(self) == -1)
11537 return NULL;
11538 length = PyUnicode_GET_LENGTH(self);
11539 kind = PyUnicode_KIND(self);
11540 data = PyUnicode_DATA(self);
11541
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011543 if (length == 1) {
11544 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11545 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11546 (Py_UNICODE_ISUPPER(ch) != 0));
11547 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011549 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011551 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011552
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 cased = 0;
11554 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 for (i = 0; i < length; i++) {
11556 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011557
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11559 if (previous_is_cased)
11560 return PyBool_FromLong(0);
11561 previous_is_cased = 1;
11562 cased = 1;
11563 }
11564 else if (Py_UNICODE_ISLOWER(ch)) {
11565 if (!previous_is_cased)
11566 return PyBool_FromLong(0);
11567 previous_is_cased = 1;
11568 cased = 1;
11569 }
11570 else
11571 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011573 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574}
11575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011576PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011579Return True if all characters in S are whitespace\n\
11580and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
11582static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011583unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 Py_ssize_t i, length;
11586 int kind;
11587 void *data;
11588
11589 if (PyUnicode_READY(self) == -1)
11590 return NULL;
11591 length = PyUnicode_GET_LENGTH(self);
11592 kind = PyUnicode_KIND(self);
11593 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (length == 1)
11597 return PyBool_FromLong(
11598 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011600 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011602 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 for (i = 0; i < length; i++) {
11605 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011606 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011609 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610}
11611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011612PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011614\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011615Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011617
11618static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011619unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011620{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 Py_ssize_t i, length;
11622 int kind;
11623 void *data;
11624
11625 if (PyUnicode_READY(self) == -1)
11626 return NULL;
11627 length = PyUnicode_GET_LENGTH(self);
11628 kind = PyUnicode_KIND(self);
11629 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011630
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011631 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 if (length == 1)
11633 return PyBool_FromLong(
11634 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011635
11636 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011638 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640 for (i = 0; i < length; i++) {
11641 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011642 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011643 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011644 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011645}
11646
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011647PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011648 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011650Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011651and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011652
11653static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011654unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 int kind;
11657 void *data;
11658 Py_ssize_t len, i;
11659
11660 if (PyUnicode_READY(self) == -1)
11661 return NULL;
11662
11663 kind = PyUnicode_KIND(self);
11664 data = PyUnicode_DATA(self);
11665 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011666
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011667 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011668 if (len == 1) {
11669 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11670 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11671 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011672
11673 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011675 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677 for (i = 0; i < len; i++) {
11678 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011679 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011680 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011681 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011682 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011683}
11684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011685PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011688Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011689False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
11691static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011692unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 Py_ssize_t i, length;
11695 int kind;
11696 void *data;
11697
11698 if (PyUnicode_READY(self) == -1)
11699 return NULL;
11700 length = PyUnicode_GET_LENGTH(self);
11701 kind = PyUnicode_KIND(self);
11702 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 if (length == 1)
11706 return PyBool_FromLong(
11707 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011709 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011710 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011711 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 for (i = 0; i < length; i++) {
11714 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011715 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011717 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718}
11719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011720PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011723Return True if all characters in S are digits\n\
11724and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725
11726static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011727unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 Py_ssize_t i, length;
11730 int kind;
11731 void *data;
11732
11733 if (PyUnicode_READY(self) == -1)
11734 return NULL;
11735 length = PyUnicode_GET_LENGTH(self);
11736 kind = PyUnicode_KIND(self);
11737 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (length == 1) {
11741 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11742 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11743 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011745 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011749 for (i = 0; i < length; i++) {
11750 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011751 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011753 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754}
11755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011756PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011759Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011760False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
11762static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011763unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011765 Py_ssize_t i, length;
11766 int kind;
11767 void *data;
11768
11769 if (PyUnicode_READY(self) == -1)
11770 return NULL;
11771 length = PyUnicode_GET_LENGTH(self);
11772 kind = PyUnicode_KIND(self);
11773 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774
Guido van Rossumd57fd912000-03-10 22:53:23 +000011775 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (length == 1)
11777 return PyBool_FromLong(
11778 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011780 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 for (i = 0; i < length; i++) {
11785 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011788 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789}
11790
Martin v. Löwis47383402007-08-15 07:32:56 +000011791int
11792PyUnicode_IsIdentifier(PyObject *self)
11793{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011794 int kind;
11795 void *data;
11796 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011797 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 if (PyUnicode_READY(self) == -1) {
11800 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 }
11803
11804 /* Special case for empty strings */
11805 if (PyUnicode_GET_LENGTH(self) == 0)
11806 return 0;
11807 kind = PyUnicode_KIND(self);
11808 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011809
11810 /* PEP 3131 says that the first character must be in
11811 XID_Start and subsequent characters in XID_Continue,
11812 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011813 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011814 letters, digits, underscore). However, given the current
11815 definition of XID_Start and XID_Continue, it is sufficient
11816 to check just for these, except that _ must be allowed
11817 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011819 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011820 return 0;
11821
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011822 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011825 return 1;
11826}
11827
11828PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011830\n\
11831Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011832to the language definition.\n\
11833\n\
11834Use keyword.iskeyword() to test for reserved identifiers\n\
11835such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011836
11837static PyObject*
11838unicode_isidentifier(PyObject *self)
11839{
11840 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11841}
11842
Georg Brandl559e5d72008-06-11 18:37:52 +000011843PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011845\n\
11846Return True if all characters in S are considered\n\
11847printable in repr() or S is empty, False otherwise.");
11848
11849static PyObject*
11850unicode_isprintable(PyObject *self)
11851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 Py_ssize_t i, length;
11853 int kind;
11854 void *data;
11855
11856 if (PyUnicode_READY(self) == -1)
11857 return NULL;
11858 length = PyUnicode_GET_LENGTH(self);
11859 kind = PyUnicode_KIND(self);
11860 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011861
11862 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (length == 1)
11864 return PyBool_FromLong(
11865 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 for (i = 0; i < length; i++) {
11868 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011869 Py_RETURN_FALSE;
11870 }
11871 }
11872 Py_RETURN_TRUE;
11873}
11874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011875PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011876 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877\n\
11878Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011879iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880
11881static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011882unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011884 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885}
11886
Martin v. Löwis18e16552006-02-15 17:27:45 +000011887static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011888unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (PyUnicode_READY(self) == -1)
11891 return -1;
11892 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893}
11894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011895PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011898Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011899done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900
11901static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011902unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011904 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 Py_UCS4 fillchar = ' ';
11906
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011907 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908 return NULL;
11909
Benjamin Petersonbac79492012-01-14 13:34:47 -050011910 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011911 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912
Victor Stinnerc4b49542011-12-11 22:44:26 +010011913 if (PyUnicode_GET_LENGTH(self) >= width)
11914 return unicode_result_unchanged(self);
11915
11916 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917}
11918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011919PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011920 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011922Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
11924static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011925unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011927 if (PyUnicode_READY(self) == -1)
11928 return NULL;
11929 if (PyUnicode_IS_ASCII(self))
11930 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011931 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932}
11933
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934#define LEFTSTRIP 0
11935#define RIGHTSTRIP 1
11936#define BOTHSTRIP 2
11937
11938/* Arrays indexed by above */
11939static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11940
11941#define STRIPNAME(i) (stripformat[i]+3)
11942
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011943/* externally visible for str.strip(unicode) */
11944PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011945_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011946{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 void *data;
11948 int kind;
11949 Py_ssize_t i, j, len;
11950 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011951 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11954 return NULL;
11955
11956 kind = PyUnicode_KIND(self);
11957 data = PyUnicode_DATA(self);
11958 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011959 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11961 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011962 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011963
Benjamin Peterson14339b62009-01-31 16:36:08 +000011964 i = 0;
11965 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011966 while (i < len) {
11967 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11968 if (!BLOOM(sepmask, ch))
11969 break;
11970 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11971 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011972 i++;
11973 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011974 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011975
Benjamin Peterson14339b62009-01-31 16:36:08 +000011976 j = len;
11977 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011978 j--;
11979 while (j >= i) {
11980 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11981 if (!BLOOM(sepmask, ch))
11982 break;
11983 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11984 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011985 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011986 }
11987
Benjamin Peterson29060642009-01-31 22:14:21 +000011988 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011989 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011990
Victor Stinner7931d9a2011-11-04 00:22:48 +010011991 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992}
11993
11994PyObject*
11995PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11996{
11997 unsigned char *data;
11998 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011999 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000
Victor Stinnerde636f32011-10-01 03:55:54 +020012001 if (PyUnicode_READY(self) == -1)
12002 return NULL;
12003
Victor Stinner684d5fd2012-05-03 02:32:34 +020012004 length = PyUnicode_GET_LENGTH(self);
12005 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012006
Victor Stinner684d5fd2012-05-03 02:32:34 +020012007 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012008 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009
Victor Stinnerde636f32011-10-01 03:55:54 +020012010 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012011 PyErr_SetString(PyExc_IndexError, "string index out of range");
12012 return NULL;
12013 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012014 if (start >= length || end < start)
12015 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012016
Victor Stinner684d5fd2012-05-03 02:32:34 +020012017 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012018 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012019 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012020 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012021 }
12022 else {
12023 kind = PyUnicode_KIND(self);
12024 data = PyUnicode_1BYTE_DATA(self);
12025 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012026 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012027 length);
12028 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030
12031static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012032do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 Py_ssize_t len, i, j;
12035
12036 if (PyUnicode_READY(self) == -1)
12037 return NULL;
12038
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012040
Victor Stinnercc7af722013-04-09 22:39:24 +020012041 if (PyUnicode_IS_ASCII(self)) {
12042 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12043
12044 i = 0;
12045 if (striptype != RIGHTSTRIP) {
12046 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012047 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012048 if (!_Py_ascii_whitespace[ch])
12049 break;
12050 i++;
12051 }
12052 }
12053
12054 j = len;
12055 if (striptype != LEFTSTRIP) {
12056 j--;
12057 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012058 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012059 if (!_Py_ascii_whitespace[ch])
12060 break;
12061 j--;
12062 }
12063 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012064 }
12065 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012066 else {
12067 int kind = PyUnicode_KIND(self);
12068 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012069
Victor Stinnercc7af722013-04-09 22:39:24 +020012070 i = 0;
12071 if (striptype != RIGHTSTRIP) {
12072 while (i < len) {
12073 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12074 if (!Py_UNICODE_ISSPACE(ch))
12075 break;
12076 i++;
12077 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012078 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012079
12080 j = len;
12081 if (striptype != LEFTSTRIP) {
12082 j--;
12083 while (j >= i) {
12084 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12085 if (!Py_UNICODE_ISSPACE(ch))
12086 break;
12087 j--;
12088 }
12089 j++;
12090 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012091 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012092
Victor Stinner7931d9a2011-11-04 00:22:48 +010012093 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094}
12095
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012096
12097static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012098do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012099{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012100 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101
Serhiy Storchakac6792272013-10-19 21:03:34 +030012102 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012103 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012104
Benjamin Peterson14339b62009-01-31 16:36:08 +000012105 if (sep != NULL && sep != Py_None) {
12106 if (PyUnicode_Check(sep))
12107 return _PyUnicode_XStrip(self, striptype, sep);
12108 else {
12109 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012110 "%s arg must be None or str",
12111 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012112 return NULL;
12113 }
12114 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012115
Benjamin Peterson14339b62009-01-31 16:36:08 +000012116 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012117}
12118
12119
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012120PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012121 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012122\n\
12123Return a copy of the string S with leading and trailing\n\
12124whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012125If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012126
12127static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012128unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012129{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012130 if (PyTuple_GET_SIZE(args) == 0)
12131 return do_strip(self, BOTHSTRIP); /* Common case */
12132 else
12133 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012134}
12135
12136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012137PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012139\n\
12140Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012141If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012142
12143static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012144unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012146 if (PyTuple_GET_SIZE(args) == 0)
12147 return do_strip(self, LEFTSTRIP); /* Common case */
12148 else
12149 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012150}
12151
12152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012153PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012155\n\
12156Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012157If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012158
12159static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 if (PyTuple_GET_SIZE(args) == 0)
12163 return do_strip(self, RIGHTSTRIP); /* Common case */
12164 else
12165 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166}
12167
12168
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012170unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012172 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012174
Serhiy Storchaka05997252013-01-26 12:14:02 +020012175 if (len < 1)
12176 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177
Victor Stinnerc4b49542011-12-11 22:44:26 +010012178 /* no repeat, return original string */
12179 if (len == 1)
12180 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012181
Benjamin Petersonbac79492012-01-14 13:34:47 -050012182 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 return NULL;
12184
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012185 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012186 PyErr_SetString(PyExc_OverflowError,
12187 "repeated string is too long");
12188 return NULL;
12189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012191
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012192 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193 if (!u)
12194 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012195 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012197 if (PyUnicode_GET_LENGTH(str) == 1) {
12198 const int kind = PyUnicode_KIND(str);
12199 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012200 if (kind == PyUnicode_1BYTE_KIND) {
12201 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012202 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012203 }
12204 else if (kind == PyUnicode_2BYTE_KIND) {
12205 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012206 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012207 ucs2[n] = fill_char;
12208 } else {
12209 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12210 assert(kind == PyUnicode_4BYTE_KIND);
12211 for (n = 0; n < len; ++n)
12212 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012213 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 }
12215 else {
12216 /* number of characters copied this far */
12217 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012218 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 char *to = (char *) PyUnicode_DATA(u);
12220 Py_MEMCPY(to, PyUnicode_DATA(str),
12221 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012222 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 n = (done <= nchars-done) ? done : nchars-done;
12224 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012225 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012226 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227 }
12228
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012229 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012230 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231}
12232
Alexander Belopolsky40018472011-02-26 01:02:56 +000012233PyObject *
12234PyUnicode_Replace(PyObject *obj,
12235 PyObject *subobj,
12236 PyObject *replobj,
12237 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238{
12239 PyObject *self;
12240 PyObject *str1;
12241 PyObject *str2;
12242 PyObject *result;
12243
12244 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012245 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012248 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012249 Py_DECREF(self);
12250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251 }
12252 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012253 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 Py_DECREF(self);
12255 Py_DECREF(str1);
12256 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012258 if (PyUnicode_READY(self) == -1 ||
12259 PyUnicode_READY(str1) == -1 ||
12260 PyUnicode_READY(str2) == -1)
12261 result = NULL;
12262 else
12263 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264 Py_DECREF(self);
12265 Py_DECREF(str1);
12266 Py_DECREF(str2);
12267 return result;
12268}
12269
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012270PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012271 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272\n\
12273Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012274old replaced by new. If the optional argument count is\n\
12275given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276
12277static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012280 PyObject *str1;
12281 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012282 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283 PyObject *result;
12284
Martin v. Löwis18e16552006-02-15 17:27:45 +000012285 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012287 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012290 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291 return NULL;
12292 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012293 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012294 Py_DECREF(str1);
12295 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012296 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012297 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12298 result = NULL;
12299 else
12300 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301
12302 Py_DECREF(str1);
12303 Py_DECREF(str2);
12304 return result;
12305}
12306
Alexander Belopolsky40018472011-02-26 01:02:56 +000012307static PyObject *
12308unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012310 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 Py_ssize_t isize;
12312 Py_ssize_t osize, squote, dquote, i, o;
12313 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012314 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012318 return NULL;
12319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 isize = PyUnicode_GET_LENGTH(unicode);
12321 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 /* Compute length of output, quote characters, and
12324 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012325 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 max = 127;
12327 squote = dquote = 0;
12328 ikind = PyUnicode_KIND(unicode);
12329 for (i = 0; i < isize; i++) {
12330 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012331 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012333 case '\'': squote++; break;
12334 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012335 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012336 incr = 2;
12337 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 default:
12339 /* Fast-path ASCII */
12340 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012341 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012343 ;
12344 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012347 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012349 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012351 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012353 if (osize > PY_SSIZE_T_MAX - incr) {
12354 PyErr_SetString(PyExc_OverflowError,
12355 "string is too long to generate repr");
12356 return NULL;
12357 }
12358 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012359 }
12360
12361 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012362 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012364 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 if (dquote)
12366 /* Both squote and dquote present. Use squote,
12367 and escape them */
12368 osize += squote;
12369 else
12370 quote = '"';
12371 }
Victor Stinner55c08782013-04-14 18:45:39 +020012372 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373
12374 repr = PyUnicode_New(osize, max);
12375 if (repr == NULL)
12376 return NULL;
12377 okind = PyUnicode_KIND(repr);
12378 odata = PyUnicode_DATA(repr);
12379
12380 PyUnicode_WRITE(okind, odata, 0, quote);
12381 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012382 if (unchanged) {
12383 _PyUnicode_FastCopyCharacters(repr, 1,
12384 unicode, 0,
12385 isize);
12386 }
12387 else {
12388 for (i = 0, o = 1; i < isize; i++) {
12389 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390
Victor Stinner55c08782013-04-14 18:45:39 +020012391 /* Escape quotes and backslashes */
12392 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012393 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012395 continue;
12396 }
12397
12398 /* Map special whitespace to '\t', \n', '\r' */
12399 if (ch == '\t') {
12400 PyUnicode_WRITE(okind, odata, o++, '\\');
12401 PyUnicode_WRITE(okind, odata, o++, 't');
12402 }
12403 else if (ch == '\n') {
12404 PyUnicode_WRITE(okind, odata, o++, '\\');
12405 PyUnicode_WRITE(okind, odata, o++, 'n');
12406 }
12407 else if (ch == '\r') {
12408 PyUnicode_WRITE(okind, odata, o++, '\\');
12409 PyUnicode_WRITE(okind, odata, o++, 'r');
12410 }
12411
12412 /* Map non-printable US ASCII to '\xhh' */
12413 else if (ch < ' ' || ch == 0x7F) {
12414 PyUnicode_WRITE(okind, odata, o++, '\\');
12415 PyUnicode_WRITE(okind, odata, o++, 'x');
12416 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12417 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12418 }
12419
12420 /* Copy ASCII characters as-is */
12421 else if (ch < 0x7F) {
12422 PyUnicode_WRITE(okind, odata, o++, ch);
12423 }
12424
12425 /* Non-ASCII characters */
12426 else {
12427 /* Map Unicode whitespace and control characters
12428 (categories Z* and C* except ASCII space)
12429 */
12430 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12431 PyUnicode_WRITE(okind, odata, o++, '\\');
12432 /* Map 8-bit characters to '\xhh' */
12433 if (ch <= 0xff) {
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 /* Map 16-bit characters to '\uxxxx' */
12439 else if (ch <= 0xffff) {
12440 PyUnicode_WRITE(okind, odata, o++, 'u');
12441 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12442 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12443 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12444 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12445 }
12446 /* Map 21-bit characters to '\U00xxxxxx' */
12447 else {
12448 PyUnicode_WRITE(okind, odata, o++, 'U');
12449 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12450 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12451 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12452 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12453 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12454 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12455 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12456 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12457 }
12458 }
12459 /* Copy characters as-is */
12460 else {
12461 PyUnicode_WRITE(okind, odata, o++, ch);
12462 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012463 }
12464 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012467 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012468 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469}
12470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012471PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012472 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473\n\
12474Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012475such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476arguments start and end are interpreted as in slice notation.\n\
12477\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012478Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479
12480static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012483 /* initialize variables to prevent gcc warning */
12484 PyObject *substring = NULL;
12485 Py_ssize_t start = 0;
12486 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012487 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488
Jesus Ceaac451502011-04-20 17:09:23 +020012489 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12490 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012491 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492
Christian Heimesea71a522013-06-29 21:17:34 +020012493 if (PyUnicode_READY(self) == -1) {
12494 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012496 }
12497 if (PyUnicode_READY(substring) == -1) {
12498 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012500 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501
Victor Stinner7931d9a2011-11-04 00:22:48 +010012502 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
12504 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 if (result == -2)
12507 return NULL;
12508
Christian Heimes217cfd12007-12-02 14:31:20 +000012509 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510}
12511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012512PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012513 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012515Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516
12517static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012518unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012520 /* initialize variables to prevent gcc warning */
12521 PyObject *substring = NULL;
12522 Py_ssize_t start = 0;
12523 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012524 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525
Jesus Ceaac451502011-04-20 17:09:23 +020012526 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12527 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012528 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529
Christian Heimesea71a522013-06-29 21:17:34 +020012530 if (PyUnicode_READY(self) == -1) {
12531 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012533 }
12534 if (PyUnicode_READY(substring) == -1) {
12535 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012536 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538
Victor Stinner7931d9a2011-11-04 00:22:48 +010012539 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540
12541 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543 if (result == -2)
12544 return NULL;
12545
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546 if (result < 0) {
12547 PyErr_SetString(PyExc_ValueError, "substring not found");
12548 return NULL;
12549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012550
Christian Heimes217cfd12007-12-02 14:31:20 +000012551 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552}
12553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012554PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012555 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012556\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012557Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012558done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012559
12560static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012561unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012563 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 Py_UCS4 fillchar = ' ';
12565
Victor Stinnere9a29352011-10-01 02:14:59 +020012566 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012568
Benjamin Petersonbac79492012-01-14 13:34:47 -050012569 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012570 return NULL;
12571
Victor Stinnerc4b49542011-12-11 22:44:26 +010012572 if (PyUnicode_GET_LENGTH(self) >= width)
12573 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012574
Victor Stinnerc4b49542011-12-11 22:44:26 +010012575 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576}
12577
Alexander Belopolsky40018472011-02-26 01:02:56 +000012578PyObject *
12579PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580{
12581 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012582
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583 s = PyUnicode_FromObject(s);
12584 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012585 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 if (sep != NULL) {
12587 sep = PyUnicode_FromObject(sep);
12588 if (sep == NULL) {
12589 Py_DECREF(s);
12590 return NULL;
12591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012592 }
12593
Victor Stinner9310abb2011-10-05 00:59:23 +020012594 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595
12596 Py_DECREF(s);
12597 Py_XDECREF(sep);
12598 return result;
12599}
12600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012601PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012602 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603\n\
12604Return a list of the words in S, using sep as the\n\
12605delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012606splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012607whitespace string is a separator and empty strings are\n\
12608removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
12610static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012611unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012613 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012615 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012617 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12618 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619 return NULL;
12620
12621 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012622 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012624 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012626 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627}
12628
Thomas Wouters477c8d52006-05-27 19:21:47 +000012629PyObject *
12630PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12631{
12632 PyObject* str_obj;
12633 PyObject* sep_obj;
12634 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 int kind1, kind2, kind;
12636 void *buf1 = NULL, *buf2 = NULL;
12637 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012638
12639 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012640 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012641 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012642 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012643 if (!sep_obj) {
12644 Py_DECREF(str_obj);
12645 return NULL;
12646 }
12647 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12648 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012649 Py_DECREF(str_obj);
12650 return NULL;
12651 }
12652
Victor Stinner14f8f022011-10-05 20:58:25 +020012653 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012655 kind = Py_MAX(kind1, kind2);
12656 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012658 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012659 if (!buf1)
12660 goto onError;
12661 buf2 = PyUnicode_DATA(sep_obj);
12662 if (kind2 != kind)
12663 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12664 if (!buf2)
12665 goto onError;
12666 len1 = PyUnicode_GET_LENGTH(str_obj);
12667 len2 = PyUnicode_GET_LENGTH(sep_obj);
12668
Benjamin Petersonead6b532011-12-20 17:23:42 -060012669 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012671 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12672 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12673 else
12674 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 break;
12676 case PyUnicode_2BYTE_KIND:
12677 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12678 break;
12679 case PyUnicode_4BYTE_KIND:
12680 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12681 break;
12682 default:
12683 assert(0);
12684 out = 0;
12685 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012686
12687 Py_DECREF(sep_obj);
12688 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 if (kind1 != kind)
12690 PyMem_Free(buf1);
12691 if (kind2 != kind)
12692 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012693
12694 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 onError:
12696 Py_DECREF(sep_obj);
12697 Py_DECREF(str_obj);
12698 if (kind1 != kind && buf1)
12699 PyMem_Free(buf1);
12700 if (kind2 != kind && buf2)
12701 PyMem_Free(buf2);
12702 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012703}
12704
12705
12706PyObject *
12707PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12708{
12709 PyObject* str_obj;
12710 PyObject* sep_obj;
12711 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 int kind1, kind2, kind;
12713 void *buf1 = NULL, *buf2 = NULL;
12714 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012715
12716 str_obj = PyUnicode_FromObject(str_in);
12717 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012718 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012719 sep_obj = PyUnicode_FromObject(sep_in);
12720 if (!sep_obj) {
12721 Py_DECREF(str_obj);
12722 return NULL;
12723 }
12724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 kind1 = PyUnicode_KIND(str_in);
12726 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012727 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728 buf1 = PyUnicode_DATA(str_in);
12729 if (kind1 != kind)
12730 buf1 = _PyUnicode_AsKind(str_in, kind);
12731 if (!buf1)
12732 goto onError;
12733 buf2 = PyUnicode_DATA(sep_obj);
12734 if (kind2 != kind)
12735 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12736 if (!buf2)
12737 goto onError;
12738 len1 = PyUnicode_GET_LENGTH(str_obj);
12739 len2 = PyUnicode_GET_LENGTH(sep_obj);
12740
Benjamin Petersonead6b532011-12-20 17:23:42 -060012741 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012743 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12744 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12745 else
12746 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012747 break;
12748 case PyUnicode_2BYTE_KIND:
12749 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12750 break;
12751 case PyUnicode_4BYTE_KIND:
12752 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12753 break;
12754 default:
12755 assert(0);
12756 out = 0;
12757 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012758
12759 Py_DECREF(sep_obj);
12760 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012761 if (kind1 != kind)
12762 PyMem_Free(buf1);
12763 if (kind2 != kind)
12764 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012765
12766 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 onError:
12768 Py_DECREF(sep_obj);
12769 Py_DECREF(str_obj);
12770 if (kind1 != kind && buf1)
12771 PyMem_Free(buf1);
12772 if (kind2 != kind && buf2)
12773 PyMem_Free(buf2);
12774 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012775}
12776
12777PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012779\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012780Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012781the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012782found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012783
12784static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012785unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012786{
Victor Stinner9310abb2011-10-05 00:59:23 +020012787 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012788}
12789
12790PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012791 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012792\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012793Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012794the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012795separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012796
12797static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012798unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012799{
Victor Stinner9310abb2011-10-05 00:59:23 +020012800 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012801}
12802
Alexander Belopolsky40018472011-02-26 01:02:56 +000012803PyObject *
12804PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012805{
12806 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012807
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012808 s = PyUnicode_FromObject(s);
12809 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012810 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012811 if (sep != NULL) {
12812 sep = PyUnicode_FromObject(sep);
12813 if (sep == NULL) {
12814 Py_DECREF(s);
12815 return NULL;
12816 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012817 }
12818
Victor Stinner9310abb2011-10-05 00:59:23 +020012819 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012820
12821 Py_DECREF(s);
12822 Py_XDECREF(sep);
12823 return result;
12824}
12825
12826PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012827 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012828\n\
12829Return a list of the words in S, using sep as the\n\
12830delimiter string, starting at the end of the string and\n\
12831working to the front. If maxsplit is given, at most maxsplit\n\
12832splits are done. If sep is not specified, any whitespace string\n\
12833is a separator.");
12834
12835static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012836unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012837{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012838 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012839 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012840 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012841
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012842 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12843 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012844 return NULL;
12845
12846 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012847 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012848 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012849 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012850 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012851 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012852}
12853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012854PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012855 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856\n\
12857Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012858Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012859is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860
12861static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012862unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012863{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012864 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012865 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012867 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12868 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869 return NULL;
12870
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012871 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872}
12873
12874static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012875PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012876{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012877 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012878}
12879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012880PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012881 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882\n\
12883Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012884and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885
12886static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012887unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012888{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012889 if (PyUnicode_READY(self) == -1)
12890 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012891 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892}
12893
Larry Hastings61272b72014-01-07 12:41:53 -080012894/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012895
Larry Hastings31826802013-10-19 00:09:25 -070012896@staticmethod
12897str.maketrans as unicode_maketrans
12898
12899 x: object
12900
12901 y: unicode=NULL
12902
12903 z: unicode=NULL
12904
12905 /
12906
12907Return a translation table usable for str.translate().
12908
12909If there is only one argument, it must be a dictionary mapping Unicode
12910ordinals (integers) or characters to Unicode ordinals, strings or None.
12911Character keys will be then converted to ordinals.
12912If there are two arguments, they must be strings of equal length, and
12913in the resulting dictionary, each character in x will be mapped to the
12914character at the same position in y. If there is a third argument, it
12915must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012916[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012917
12918PyDoc_STRVAR(unicode_maketrans__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -080012919"maketrans(x, y=None, z=None, /)\n"
12920"--\n"
12921"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012922"Return a translation table usable for str.translate().\n"
12923"\n"
Larry Hastings31826802013-10-19 00:09:25 -070012924"If there is only one argument, it must be a dictionary mapping Unicode\n"
12925"ordinals (integers) or characters to Unicode ordinals, strings or None.\n"
12926"Character keys will be then converted to ordinals.\n"
12927"If there are two arguments, they must be strings of equal length, and\n"
12928"in the resulting dictionary, each character in x will be mapped to the\n"
12929"character at the same position in y. If there is a third argument, it\n"
12930"must be a string, whose characters will be mapped to None in the result.");
12931
12932#define UNICODE_MAKETRANS_METHODDEF \
12933 {"maketrans", (PyCFunction)unicode_maketrans, METH_VARARGS|METH_STATIC, unicode_maketrans__doc__},
12934
12935static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012936unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z);
Larry Hastings31826802013-10-19 00:09:25 -070012937
12938static PyObject *
Larry Hastingsebdcb502013-11-23 14:54:00 -080012939unicode_maketrans(void *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012940{
Larry Hastings31826802013-10-19 00:09:25 -070012941 PyObject *return_value = NULL;
12942 PyObject *x;
12943 PyObject *y = NULL;
12944 PyObject *z = NULL;
12945
12946 if (!PyArg_ParseTuple(args,
12947 "O|UU:maketrans",
12948 &x, &y, &z))
12949 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -080012950 return_value = unicode_maketrans_impl(x, y, z);
Larry Hastings31826802013-10-19 00:09:25 -070012951
12952exit:
12953 return return_value;
12954}
12955
12956static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012957unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Larry Hastings2623c8c2014-02-08 22:15:29 -080012958/*[clinic end generated code: output=566edf630f77436a input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012959{
Georg Brandlceee0772007-11-27 23:48:05 +000012960 PyObject *new = NULL, *key, *value;
12961 Py_ssize_t i = 0;
12962 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012963
Georg Brandlceee0772007-11-27 23:48:05 +000012964 new = PyDict_New();
12965 if (!new)
12966 return NULL;
12967 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012968 int x_kind, y_kind, z_kind;
12969 void *x_data, *y_data, *z_data;
12970
Georg Brandlceee0772007-11-27 23:48:05 +000012971 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012972 if (!PyUnicode_Check(x)) {
12973 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12974 "be a string if there is a second argument");
12975 goto err;
12976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012978 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12979 "arguments must have equal length");
12980 goto err;
12981 }
12982 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 x_kind = PyUnicode_KIND(x);
12984 y_kind = PyUnicode_KIND(y);
12985 x_data = PyUnicode_DATA(x);
12986 y_data = PyUnicode_DATA(y);
12987 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12988 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012989 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012990 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012991 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012992 if (!value) {
12993 Py_DECREF(key);
12994 goto err;
12995 }
Georg Brandlceee0772007-11-27 23:48:05 +000012996 res = PyDict_SetItem(new, key, value);
12997 Py_DECREF(key);
12998 Py_DECREF(value);
12999 if (res < 0)
13000 goto err;
13001 }
13002 /* create entries for deleting chars in z */
13003 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013004 z_kind = PyUnicode_KIND(z);
13005 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013006 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013007 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013008 if (!key)
13009 goto err;
13010 res = PyDict_SetItem(new, key, Py_None);
13011 Py_DECREF(key);
13012 if (res < 0)
13013 goto err;
13014 }
13015 }
13016 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 int kind;
13018 void *data;
13019
Georg Brandlceee0772007-11-27 23:48:05 +000013020 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013021 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013022 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13023 "to maketrans it must be a dict");
13024 goto err;
13025 }
13026 /* copy entries into the new dict, converting string keys to int keys */
13027 while (PyDict_Next(x, &i, &key, &value)) {
13028 if (PyUnicode_Check(key)) {
13029 /* convert string keys to integer keys */
13030 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013031 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013032 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13033 "table must be of length 1");
13034 goto err;
13035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 kind = PyUnicode_KIND(key);
13037 data = PyUnicode_DATA(key);
13038 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013039 if (!newkey)
13040 goto err;
13041 res = PyDict_SetItem(new, newkey, value);
13042 Py_DECREF(newkey);
13043 if (res < 0)
13044 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013045 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013046 /* just keep integer keys */
13047 if (PyDict_SetItem(new, key, value) < 0)
13048 goto err;
13049 } else {
13050 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13051 "be strings or integers");
13052 goto err;
13053 }
13054 }
13055 }
13056 return new;
13057 err:
13058 Py_DECREF(new);
13059 return NULL;
13060}
13061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013062PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013063 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064\n\
13065Return a copy of the string S, where all characters have been mapped\n\
13066through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000013067Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000013068Unmapped characters are left untouched. Characters mapped to None\n\
13069are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070
13071static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013072unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013074 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075}
13076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013077PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013080Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081
13082static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013083unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013085 if (PyUnicode_READY(self) == -1)
13086 return NULL;
13087 if (PyUnicode_IS_ASCII(self))
13088 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013089 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090}
13091
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013092PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013095Pad a numeric string S with zeros on the left, to fill a field\n\
13096of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097
13098static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013099unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013101 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013102 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013103 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 int kind;
13105 void *data;
13106 Py_UCS4 chr;
13107
Martin v. Löwis18e16552006-02-15 17:27:45 +000013108 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109 return NULL;
13110
Benjamin Petersonbac79492012-01-14 13:34:47 -050013111 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113
Victor Stinnerc4b49542011-12-11 22:44:26 +010013114 if (PyUnicode_GET_LENGTH(self) >= width)
13115 return unicode_result_unchanged(self);
13116
13117 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118
13119 u = pad(self, fill, 0, '0');
13120
Walter Dörwald068325e2002-04-15 13:36:47 +000013121 if (u == NULL)
13122 return NULL;
13123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 kind = PyUnicode_KIND(u);
13125 data = PyUnicode_DATA(u);
13126 chr = PyUnicode_READ(kind, data, fill);
13127
13128 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013129 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013130 PyUnicode_WRITE(kind, data, 0, chr);
13131 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013132 }
13133
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013134 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013135 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013137
13138#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013139static PyObject *
13140unicode__decimal2ascii(PyObject *self)
13141{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013143}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013144#endif
13145
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013146PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013147 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013148\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013149Return True if S starts with the specified prefix, False otherwise.\n\
13150With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013151With optional end, stop comparing S at that position.\n\
13152prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153
13154static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013155unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013158 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013159 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013160 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013161 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013162 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163
Jesus Ceaac451502011-04-20 17:09:23 +020013164 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013166 if (PyTuple_Check(subobj)) {
13167 Py_ssize_t i;
13168 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013169 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013170 if (substring == NULL)
13171 return NULL;
13172 result = tailmatch(self, substring, start, end, -1);
13173 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013174 if (result == -1)
13175 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013176 if (result) {
13177 Py_RETURN_TRUE;
13178 }
13179 }
13180 /* nothing matched */
13181 Py_RETURN_FALSE;
13182 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013183 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013184 if (substring == NULL) {
13185 if (PyErr_ExceptionMatches(PyExc_TypeError))
13186 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13187 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013188 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013189 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013190 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191 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 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195}
13196
13197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013198PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013201Return True if S ends with the specified suffix, False otherwise.\n\
13202With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013203With optional end, stop comparing S at that position.\n\
13204suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205
13206static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013207unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013210 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013211 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013212 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013213 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013214 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215
Jesus Ceaac451502011-04-20 17:09:23 +020013216 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013218 if (PyTuple_Check(subobj)) {
13219 Py_ssize_t i;
13220 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013221 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013224 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013225 result = tailmatch(self, substring, start, end, +1);
13226 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013227 if (result == -1)
13228 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013229 if (result) {
13230 Py_RETURN_TRUE;
13231 }
13232 }
13233 Py_RETURN_FALSE;
13234 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013235 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013236 if (substring == NULL) {
13237 if (PyErr_ExceptionMatches(PyExc_TypeError))
13238 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13239 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013241 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013242 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013243 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013244 if (result == -1)
13245 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013246 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247}
13248
Victor Stinner202fdca2012-05-07 12:47:02 +020013249Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013250_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013251{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013252 if (!writer->readonly)
13253 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13254 else {
13255 /* Copy-on-write mode: set buffer size to 0 so
13256 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13257 * next write. */
13258 writer->size = 0;
13259 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013260 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13261 writer->data = PyUnicode_DATA(writer->buffer);
13262 writer->kind = PyUnicode_KIND(writer->buffer);
13263}
13264
Victor Stinnerd3f08822012-05-29 12:57:52 +020013265void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013266_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013267{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013268 memset(writer, 0, sizeof(*writer));
13269#ifdef Py_DEBUG
13270 writer->kind = 5; /* invalid kind */
13271#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013272 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013273}
13274
Victor Stinnerd3f08822012-05-29 12:57:52 +020013275int
13276_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13277 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013278{
Victor Stinner6989ba02013-11-18 21:08:39 +010013279#ifdef MS_WINDOWS
13280 /* On Windows, overallocate by 50% is the best factor */
13281# define OVERALLOCATE_FACTOR 2
13282#else
13283 /* On Linux, overallocate by 25% is the best factor */
13284# define OVERALLOCATE_FACTOR 4
13285#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013286 Py_ssize_t newlen;
13287 PyObject *newbuffer;
13288
Victor Stinnerd3f08822012-05-29 12:57:52 +020013289 assert(length > 0);
13290
Victor Stinner202fdca2012-05-07 12:47:02 +020013291 if (length > PY_SSIZE_T_MAX - writer->pos) {
13292 PyErr_NoMemory();
13293 return -1;
13294 }
13295 newlen = writer->pos + length;
13296
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013297 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013298
Victor Stinnerd3f08822012-05-29 12:57:52 +020013299 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013300 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013301 if (writer->overallocate
13302 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13303 /* overallocate to limit the number of realloc() */
13304 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013305 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013306 if (newlen < writer->min_length)
13307 newlen = writer->min_length;
13308
Victor Stinnerd3f08822012-05-29 12:57:52 +020013309 writer->buffer = PyUnicode_New(newlen, maxchar);
13310 if (writer->buffer == NULL)
13311 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013312 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013313 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013314 if (writer->overallocate
13315 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13316 /* overallocate to limit the number of realloc() */
13317 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013318 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013319 if (newlen < writer->min_length)
13320 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013322 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013323 /* resize + widen */
13324 newbuffer = PyUnicode_New(newlen, maxchar);
13325 if (newbuffer == NULL)
13326 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013327 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13328 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013329 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013330 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013331 }
13332 else {
13333 newbuffer = resize_compact(writer->buffer, newlen);
13334 if (newbuffer == NULL)
13335 return -1;
13336 }
13337 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013338 }
13339 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013340 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013341 newbuffer = PyUnicode_New(writer->size, maxchar);
13342 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013343 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013344 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13345 writer->buffer, 0, writer->pos);
13346 Py_DECREF(writer->buffer);
13347 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013348 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013349 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013350 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013351
13352#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013353}
13354
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013355Py_LOCAL_INLINE(int)
13356_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013357{
13358 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13359 return -1;
13360 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13361 writer->pos++;
13362 return 0;
13363}
13364
13365int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013366_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13367{
13368 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13369}
13370
13371int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013372_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13373{
13374 Py_UCS4 maxchar;
13375 Py_ssize_t len;
13376
13377 if (PyUnicode_READY(str) == -1)
13378 return -1;
13379 len = PyUnicode_GET_LENGTH(str);
13380 if (len == 0)
13381 return 0;
13382 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13383 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013384 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013385 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013386 Py_INCREF(str);
13387 writer->buffer = str;
13388 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013389 writer->pos += len;
13390 return 0;
13391 }
13392 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13393 return -1;
13394 }
13395 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13396 str, 0, len);
13397 writer->pos += len;
13398 return 0;
13399}
13400
Victor Stinnere215d962012-10-06 23:03:36 +020013401int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013402_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13403 Py_ssize_t start, Py_ssize_t end)
13404{
13405 Py_UCS4 maxchar;
13406 Py_ssize_t len;
13407
13408 if (PyUnicode_READY(str) == -1)
13409 return -1;
13410
13411 assert(0 <= start);
13412 assert(end <= PyUnicode_GET_LENGTH(str));
13413 assert(start <= end);
13414
13415 if (end == 0)
13416 return 0;
13417
13418 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13419 return _PyUnicodeWriter_WriteStr(writer, str);
13420
13421 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13422 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13423 else
13424 maxchar = writer->maxchar;
13425 len = end - start;
13426
13427 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13428 return -1;
13429
13430 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13431 str, start, len);
13432 writer->pos += len;
13433 return 0;
13434}
13435
13436int
Victor Stinner4a587072013-11-19 12:54:53 +010013437_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13438 const char *ascii, Py_ssize_t len)
13439{
13440 if (len == -1)
13441 len = strlen(ascii);
13442
13443 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13444
13445 if (writer->buffer == NULL && !writer->overallocate) {
13446 PyObject *str;
13447
13448 str = _PyUnicode_FromASCII(ascii, len);
13449 if (str == NULL)
13450 return -1;
13451
13452 writer->readonly = 1;
13453 writer->buffer = str;
13454 _PyUnicodeWriter_Update(writer);
13455 writer->pos += len;
13456 return 0;
13457 }
13458
13459 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13460 return -1;
13461
13462 switch (writer->kind)
13463 {
13464 case PyUnicode_1BYTE_KIND:
13465 {
13466 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13467 Py_UCS1 *data = writer->data;
13468
13469 Py_MEMCPY(data + writer->pos, str, len);
13470 break;
13471 }
13472 case PyUnicode_2BYTE_KIND:
13473 {
13474 _PyUnicode_CONVERT_BYTES(
13475 Py_UCS1, Py_UCS2,
13476 ascii, ascii + len,
13477 (Py_UCS2 *)writer->data + writer->pos);
13478 break;
13479 }
13480 case PyUnicode_4BYTE_KIND:
13481 {
13482 _PyUnicode_CONVERT_BYTES(
13483 Py_UCS1, Py_UCS4,
13484 ascii, ascii + len,
13485 (Py_UCS4 *)writer->data + writer->pos);
13486 break;
13487 }
13488 default:
13489 assert(0);
13490 }
13491
13492 writer->pos += len;
13493 return 0;
13494}
13495
13496int
13497_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13498 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013499{
13500 Py_UCS4 maxchar;
13501
13502 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13503 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13504 return -1;
13505 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13506 writer->pos += len;
13507 return 0;
13508}
13509
Victor Stinnerd3f08822012-05-29 12:57:52 +020013510PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013511_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013512{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013513 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013514 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013515 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013516 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013518 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013519 str = writer->buffer;
13520 writer->buffer = NULL;
13521 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13522 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013523 }
13524 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13525 PyObject *newbuffer;
13526 newbuffer = resize_compact(writer->buffer, writer->pos);
13527 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013528 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013529 return NULL;
13530 }
13531 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013532 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013533 str = writer->buffer;
13534 writer->buffer = NULL;
13535 assert(_PyUnicode_CheckConsistency(str, 1));
13536 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013537}
13538
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013540_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013541{
13542 Py_CLEAR(writer->buffer);
13543}
13544
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013545#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013546
13547PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013549\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013550Return a formatted version of S, using substitutions from args and kwargs.\n\
13551The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013552
Eric Smith27bbca62010-11-04 17:06:58 +000013553PyDoc_STRVAR(format_map__doc__,
13554 "S.format_map(mapping) -> str\n\
13555\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013556Return a formatted version of S, using substitutions from mapping.\n\
13557The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013558
Eric Smith4a7d76d2008-05-30 18:10:19 +000013559static PyObject *
13560unicode__format__(PyObject* self, PyObject* args)
13561{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013562 PyObject *format_spec;
13563 _PyUnicodeWriter writer;
13564 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013565
13566 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13567 return NULL;
13568
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569 if (PyUnicode_READY(self) == -1)
13570 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013571 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13573 self, format_spec, 0,
13574 PyUnicode_GET_LENGTH(format_spec));
13575 if (ret == -1) {
13576 _PyUnicodeWriter_Dealloc(&writer);
13577 return NULL;
13578 }
13579 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013580}
13581
Eric Smith8c663262007-08-25 02:26:07 +000013582PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013583 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013584\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013585Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013586
13587static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013588unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013590 Py_ssize_t size;
13591
13592 /* If it's a compact object, account for base structure +
13593 character data. */
13594 if (PyUnicode_IS_COMPACT_ASCII(v))
13595 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13596 else if (PyUnicode_IS_COMPACT(v))
13597 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013598 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013599 else {
13600 /* If it is a two-block object, account for base object, and
13601 for character block if present. */
13602 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013603 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013604 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013605 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013606 }
13607 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013608 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013609 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013610 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013611 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013612 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613
13614 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013615}
13616
13617PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013618 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013619
13620static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013621unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013622{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013623 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 if (!copy)
13625 return NULL;
13626 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013627}
13628
Guido van Rossumd57fd912000-03-10 22:53:23 +000013629static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013630 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013631 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013632 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13633 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013634 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13635 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013636 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013637 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13638 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13639 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013640 {"expandtabs", (PyCFunction) unicode_expandtabs,
13641 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013642 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013643 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013644 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13645 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13646 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013647 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013648 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13649 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13650 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013651 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013652 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013653 {"splitlines", (PyCFunction) unicode_splitlines,
13654 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013655 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013656 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13657 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13658 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13659 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13660 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13661 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13662 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13663 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13664 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13665 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13666 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13667 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13668 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13669 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013670 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013671 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013672 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013673 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013674 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013675 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013676 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013677 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013678#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013679 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013680 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013681#endif
13682
Benjamin Peterson14339b62009-01-31 16:36:08 +000013683 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013684 {NULL, NULL}
13685};
13686
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013687static PyObject *
13688unicode_mod(PyObject *v, PyObject *w)
13689{
Brian Curtindfc80e32011-08-10 20:28:54 -050013690 if (!PyUnicode_Check(v))
13691 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013693}
13694
13695static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013696 0, /*nb_add*/
13697 0, /*nb_subtract*/
13698 0, /*nb_multiply*/
13699 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013700};
13701
Guido van Rossumd57fd912000-03-10 22:53:23 +000013702static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013703 (lenfunc) unicode_length, /* sq_length */
13704 PyUnicode_Concat, /* sq_concat */
13705 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13706 (ssizeargfunc) unicode_getitem, /* sq_item */
13707 0, /* sq_slice */
13708 0, /* sq_ass_item */
13709 0, /* sq_ass_slice */
13710 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013711};
13712
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013713static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013714unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013715{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013716 if (PyUnicode_READY(self) == -1)
13717 return NULL;
13718
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013719 if (PyIndex_Check(item)) {
13720 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013721 if (i == -1 && PyErr_Occurred())
13722 return NULL;
13723 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013724 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013725 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013726 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013727 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013728 PyObject *result;
13729 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013730 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013731 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013733 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013735 return NULL;
13736 }
13737
13738 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013739 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013740 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013741 slicelength == PyUnicode_GET_LENGTH(self)) {
13742 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013743 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013744 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013745 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013746 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013747 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013748 src_kind = PyUnicode_KIND(self);
13749 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013750 if (!PyUnicode_IS_ASCII(self)) {
13751 kind_limit = kind_maxchar_limit(src_kind);
13752 max_char = 0;
13753 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13754 ch = PyUnicode_READ(src_kind, src_data, cur);
13755 if (ch > max_char) {
13756 max_char = ch;
13757 if (max_char >= kind_limit)
13758 break;
13759 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013760 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013761 }
Victor Stinner55c99112011-10-13 01:17:06 +020013762 else
13763 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013764 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013765 if (result == NULL)
13766 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013767 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013768 dest_data = PyUnicode_DATA(result);
13769
13770 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013771 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13772 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013773 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013774 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013775 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013776 } else {
13777 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13778 return NULL;
13779 }
13780}
13781
13782static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013783 (lenfunc)unicode_length, /* mp_length */
13784 (binaryfunc)unicode_subscript, /* mp_subscript */
13785 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013786};
13787
Guido van Rossumd57fd912000-03-10 22:53:23 +000013788
Guido van Rossumd57fd912000-03-10 22:53:23 +000013789/* Helpers for PyUnicode_Format() */
13790
Victor Stinnera47082312012-10-04 02:19:54 +020013791struct unicode_formatter_t {
13792 PyObject *args;
13793 int args_owned;
13794 Py_ssize_t arglen, argidx;
13795 PyObject *dict;
13796
13797 enum PyUnicode_Kind fmtkind;
13798 Py_ssize_t fmtcnt, fmtpos;
13799 void *fmtdata;
13800 PyObject *fmtstr;
13801
13802 _PyUnicodeWriter writer;
13803};
13804
13805struct unicode_format_arg_t {
13806 Py_UCS4 ch;
13807 int flags;
13808 Py_ssize_t width;
13809 int prec;
13810 int sign;
13811};
13812
Guido van Rossumd57fd912000-03-10 22:53:23 +000013813static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013814unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013815{
Victor Stinnera47082312012-10-04 02:19:54 +020013816 Py_ssize_t argidx = ctx->argidx;
13817
13818 if (argidx < ctx->arglen) {
13819 ctx->argidx++;
13820 if (ctx->arglen < 0)
13821 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013822 else
Victor Stinnera47082312012-10-04 02:19:54 +020013823 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013824 }
13825 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827 return NULL;
13828}
13829
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013830/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013831
Victor Stinnera47082312012-10-04 02:19:54 +020013832/* Format a float into the writer if the writer is not NULL, or into *p_output
13833 otherwise.
13834
13835 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013836static int
Victor Stinnera47082312012-10-04 02:19:54 +020013837formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13838 PyObject **p_output,
13839 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013840{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013841 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013842 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013843 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013844 int prec;
13845 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013846
Guido van Rossumd57fd912000-03-10 22:53:23 +000013847 x = PyFloat_AsDouble(v);
13848 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013849 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013850
Victor Stinnera47082312012-10-04 02:19:54 +020013851 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013852 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013853 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013854
Victor Stinnera47082312012-10-04 02:19:54 +020013855 if (arg->flags & F_ALT)
13856 dtoa_flags = Py_DTSF_ALT;
13857 else
13858 dtoa_flags = 0;
13859 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013860 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013861 return -1;
13862 len = strlen(p);
13863 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013864 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013865 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013866 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013867 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013868 }
13869 else
13870 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013871 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013872 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013873}
13874
Victor Stinnerd0880d52012-04-27 23:40:13 +020013875/* formatlong() emulates the format codes d, u, o, x and X, and
13876 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13877 * Python's regular ints.
13878 * Return value: a new PyUnicodeObject*, or NULL if error.
13879 * The output string is of the form
13880 * "-"? ("0x" | "0X")? digit+
13881 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13882 * set in flags. The case of hex digits will be correct,
13883 * There will be at least prec digits, zero-filled on the left if
13884 * necessary to get that many.
13885 * val object to be converted
13886 * flags bitmask of format flags; only F_ALT is looked at
13887 * prec minimum number of digits; 0-fill on left if needed
13888 * type a character in [duoxX]; u acts the same as d
13889 *
13890 * CAUTION: o, x and X conversions on regular ints can never
13891 * produce a '-' sign, but can for Python's unbounded ints.
13892 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013893PyObject *
13894_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013895{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013896 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013897 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013898 Py_ssize_t i;
13899 int sign; /* 1 if '-', else 0 */
13900 int len; /* number of characters */
13901 Py_ssize_t llen;
13902 int numdigits; /* len == numnondigits + numdigits */
13903 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013904
Victor Stinnerd0880d52012-04-27 23:40:13 +020013905 /* Avoid exceeding SSIZE_T_MAX */
13906 if (prec > INT_MAX-3) {
13907 PyErr_SetString(PyExc_OverflowError,
13908 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013910 }
13911
13912 assert(PyLong_Check(val));
13913
13914 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013915 default:
13916 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013917 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013918 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013919 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013920 /* int and int subclasses should print numerically when a numeric */
13921 /* format code is used (see issue18780) */
13922 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013923 break;
13924 case 'o':
13925 numnondigits = 2;
13926 result = PyNumber_ToBase(val, 8);
13927 break;
13928 case 'x':
13929 case 'X':
13930 numnondigits = 2;
13931 result = PyNumber_ToBase(val, 16);
13932 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013933 }
13934 if (!result)
13935 return NULL;
13936
13937 assert(unicode_modifiable(result));
13938 assert(PyUnicode_IS_READY(result));
13939 assert(PyUnicode_IS_ASCII(result));
13940
13941 /* To modify the string in-place, there can only be one reference. */
13942 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013943 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 PyErr_BadInternalCall();
13945 return NULL;
13946 }
13947 buf = PyUnicode_DATA(result);
13948 llen = PyUnicode_GET_LENGTH(result);
13949 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013950 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013951 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013952 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013953 return NULL;
13954 }
13955 len = (int)llen;
13956 sign = buf[0] == '-';
13957 numnondigits += sign;
13958 numdigits = len - numnondigits;
13959 assert(numdigits > 0);
13960
13961 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013962 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013963 (type == 'o' || type == 'x' || type == 'X'))) {
13964 assert(buf[sign] == '0');
13965 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13966 buf[sign+1] == 'o');
13967 numnondigits -= 2;
13968 buf += 2;
13969 len -= 2;
13970 if (sign)
13971 buf[0] = '-';
13972 assert(len == numnondigits + numdigits);
13973 assert(numdigits > 0);
13974 }
13975
13976 /* Fill with leading zeroes to meet minimum width. */
13977 if (prec > numdigits) {
13978 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13979 numnondigits + prec);
13980 char *b1;
13981 if (!r1) {
13982 Py_DECREF(result);
13983 return NULL;
13984 }
13985 b1 = PyBytes_AS_STRING(r1);
13986 for (i = 0; i < numnondigits; ++i)
13987 *b1++ = *buf++;
13988 for (i = 0; i < prec - numdigits; i++)
13989 *b1++ = '0';
13990 for (i = 0; i < numdigits; i++)
13991 *b1++ = *buf++;
13992 *b1 = '\0';
13993 Py_DECREF(result);
13994 result = r1;
13995 buf = PyBytes_AS_STRING(result);
13996 len = numnondigits + prec;
13997 }
13998
13999 /* Fix up case for hex conversions. */
14000 if (type == 'X') {
14001 /* Need to convert all lower case letters to upper case.
14002 and need to convert 0x to 0X (and -0x to -0X). */
14003 for (i = 0; i < len; i++)
14004 if (buf[i] >= 'a' && buf[i] <= 'x')
14005 buf[i] -= 'a'-'A';
14006 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014007 if (!PyUnicode_Check(result)
14008 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014009 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014010 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014011 Py_DECREF(result);
14012 result = unicode;
14013 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014014 else if (len != PyUnicode_GET_LENGTH(result)) {
14015 if (PyUnicode_Resize(&result, len) < 0)
14016 Py_CLEAR(result);
14017 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014019}
14020
Ethan Furmandf3ed242014-01-05 06:50:30 -080014021/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014022 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014023 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014024 * -1 and raise an exception on error */
14025static int
Victor Stinnera47082312012-10-04 02:19:54 +020014026mainformatlong(PyObject *v,
14027 struct unicode_format_arg_t *arg,
14028 PyObject **p_output,
14029 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014030{
14031 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014032 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014033
14034 if (!PyNumber_Check(v))
14035 goto wrongtype;
14036
Ethan Furman9ab74802014-03-21 06:38:46 -070014037 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014038 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014039 if (type == 'o' || type == 'x' || type == 'X') {
14040 iobj = PyNumber_Index(v);
14041 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014042 if (PyErr_ExceptionMatches(PyExc_TypeError))
14043 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014044 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014045 }
14046 }
14047 else {
14048 iobj = PyNumber_Long(v);
14049 if (iobj == NULL ) {
14050 if (PyErr_ExceptionMatches(PyExc_TypeError))
14051 goto wrongtype;
14052 return -1;
14053 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014054 }
14055 assert(PyLong_Check(iobj));
14056 }
14057 else {
14058 iobj = v;
14059 Py_INCREF(iobj);
14060 }
14061
14062 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014063 && arg->width == -1 && arg->prec == -1
14064 && !(arg->flags & (F_SIGN | F_BLANK))
14065 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014066 {
14067 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014068 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014069 int base;
14070
Victor Stinnera47082312012-10-04 02:19:54 +020014071 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014072 {
14073 default:
14074 assert(0 && "'type' not in [diuoxX]");
14075 case 'd':
14076 case 'i':
14077 case 'u':
14078 base = 10;
14079 break;
14080 case 'o':
14081 base = 8;
14082 break;
14083 case 'x':
14084 case 'X':
14085 base = 16;
14086 break;
14087 }
14088
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014089 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14090 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014091 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014092 }
14093 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014094 return 1;
14095 }
14096
Ethan Furmanb95b5612015-01-23 20:05:18 -080014097 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014098 Py_DECREF(iobj);
14099 if (res == NULL)
14100 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014101 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014102 return 0;
14103
14104wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014105 switch(type)
14106 {
14107 case 'o':
14108 case 'x':
14109 case 'X':
14110 PyErr_Format(PyExc_TypeError,
14111 "%%%c format: an integer is required, "
14112 "not %.200s",
14113 type, Py_TYPE(v)->tp_name);
14114 break;
14115 default:
14116 PyErr_Format(PyExc_TypeError,
14117 "%%%c format: a number is required, "
14118 "not %.200s",
14119 type, Py_TYPE(v)->tp_name);
14120 break;
14121 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014122 return -1;
14123}
14124
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014125static Py_UCS4
14126formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014127{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014128 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014129 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014130 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014131 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014132 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 goto onError;
14134 }
14135 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014136 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014137 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014138 /* make sure number is a type of integer */
14139 if (!PyLong_Check(v)) {
14140 iobj = PyNumber_Index(v);
14141 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014142 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014143 }
14144 v = iobj;
14145 Py_DECREF(iobj);
14146 }
14147 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014148 x = PyLong_AsLong(v);
14149 if (x == -1 && PyErr_Occurred())
14150 goto onError;
14151
Victor Stinner8faf8212011-12-08 22:14:11 +010014152 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014153 PyErr_SetString(PyExc_OverflowError,
14154 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014155 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014156 }
14157
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014158 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014159 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014160
Benjamin Peterson29060642009-01-31 22:14:21 +000014161 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014162 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014163 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014164 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014165}
14166
Victor Stinnera47082312012-10-04 02:19:54 +020014167/* Parse options of an argument: flags, width, precision.
14168 Handle also "%(name)" syntax.
14169
14170 Return 0 if the argument has been formatted into arg->str.
14171 Return 1 if the argument has been written into ctx->writer,
14172 Raise an exception and return -1 on error. */
14173static int
14174unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14175 struct unicode_format_arg_t *arg)
14176{
14177#define FORMAT_READ(ctx) \
14178 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14179
14180 PyObject *v;
14181
Victor Stinnera47082312012-10-04 02:19:54 +020014182 if (arg->ch == '(') {
14183 /* Get argument value from a dictionary. Example: "%(name)s". */
14184 Py_ssize_t keystart;
14185 Py_ssize_t keylen;
14186 PyObject *key;
14187 int pcount = 1;
14188
14189 if (ctx->dict == NULL) {
14190 PyErr_SetString(PyExc_TypeError,
14191 "format requires a mapping");
14192 return -1;
14193 }
14194 ++ctx->fmtpos;
14195 --ctx->fmtcnt;
14196 keystart = ctx->fmtpos;
14197 /* Skip over balanced parentheses */
14198 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14199 arg->ch = FORMAT_READ(ctx);
14200 if (arg->ch == ')')
14201 --pcount;
14202 else if (arg->ch == '(')
14203 ++pcount;
14204 ctx->fmtpos++;
14205 }
14206 keylen = ctx->fmtpos - keystart - 1;
14207 if (ctx->fmtcnt < 0 || pcount > 0) {
14208 PyErr_SetString(PyExc_ValueError,
14209 "incomplete format key");
14210 return -1;
14211 }
14212 key = PyUnicode_Substring(ctx->fmtstr,
14213 keystart, keystart + keylen);
14214 if (key == NULL)
14215 return -1;
14216 if (ctx->args_owned) {
14217 Py_DECREF(ctx->args);
14218 ctx->args_owned = 0;
14219 }
14220 ctx->args = PyObject_GetItem(ctx->dict, key);
14221 Py_DECREF(key);
14222 if (ctx->args == NULL)
14223 return -1;
14224 ctx->args_owned = 1;
14225 ctx->arglen = -1;
14226 ctx->argidx = -2;
14227 }
14228
14229 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014230 while (--ctx->fmtcnt >= 0) {
14231 arg->ch = FORMAT_READ(ctx);
14232 ctx->fmtpos++;
14233 switch (arg->ch) {
14234 case '-': arg->flags |= F_LJUST; continue;
14235 case '+': arg->flags |= F_SIGN; continue;
14236 case ' ': arg->flags |= F_BLANK; continue;
14237 case '#': arg->flags |= F_ALT; continue;
14238 case '0': arg->flags |= F_ZERO; continue;
14239 }
14240 break;
14241 }
14242
14243 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014244 if (arg->ch == '*') {
14245 v = unicode_format_getnextarg(ctx);
14246 if (v == NULL)
14247 return -1;
14248 if (!PyLong_Check(v)) {
14249 PyErr_SetString(PyExc_TypeError,
14250 "* wants int");
14251 return -1;
14252 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014253 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014254 if (arg->width == -1 && PyErr_Occurred())
14255 return -1;
14256 if (arg->width < 0) {
14257 arg->flags |= F_LJUST;
14258 arg->width = -arg->width;
14259 }
14260 if (--ctx->fmtcnt >= 0) {
14261 arg->ch = FORMAT_READ(ctx);
14262 ctx->fmtpos++;
14263 }
14264 }
14265 else if (arg->ch >= '0' && arg->ch <= '9') {
14266 arg->width = arg->ch - '0';
14267 while (--ctx->fmtcnt >= 0) {
14268 arg->ch = FORMAT_READ(ctx);
14269 ctx->fmtpos++;
14270 if (arg->ch < '0' || arg->ch > '9')
14271 break;
14272 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14273 mixing signed and unsigned comparison. Since arg->ch is between
14274 '0' and '9', casting to int is safe. */
14275 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14276 PyErr_SetString(PyExc_ValueError,
14277 "width too big");
14278 return -1;
14279 }
14280 arg->width = arg->width*10 + (arg->ch - '0');
14281 }
14282 }
14283
14284 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014285 if (arg->ch == '.') {
14286 arg->prec = 0;
14287 if (--ctx->fmtcnt >= 0) {
14288 arg->ch = FORMAT_READ(ctx);
14289 ctx->fmtpos++;
14290 }
14291 if (arg->ch == '*') {
14292 v = unicode_format_getnextarg(ctx);
14293 if (v == NULL)
14294 return -1;
14295 if (!PyLong_Check(v)) {
14296 PyErr_SetString(PyExc_TypeError,
14297 "* wants int");
14298 return -1;
14299 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014300 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014301 if (arg->prec == -1 && PyErr_Occurred())
14302 return -1;
14303 if (arg->prec < 0)
14304 arg->prec = 0;
14305 if (--ctx->fmtcnt >= 0) {
14306 arg->ch = FORMAT_READ(ctx);
14307 ctx->fmtpos++;
14308 }
14309 }
14310 else if (arg->ch >= '0' && arg->ch <= '9') {
14311 arg->prec = arg->ch - '0';
14312 while (--ctx->fmtcnt >= 0) {
14313 arg->ch = FORMAT_READ(ctx);
14314 ctx->fmtpos++;
14315 if (arg->ch < '0' || arg->ch > '9')
14316 break;
14317 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14318 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014319 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014320 return -1;
14321 }
14322 arg->prec = arg->prec*10 + (arg->ch - '0');
14323 }
14324 }
14325 }
14326
14327 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14328 if (ctx->fmtcnt >= 0) {
14329 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14330 if (--ctx->fmtcnt >= 0) {
14331 arg->ch = FORMAT_READ(ctx);
14332 ctx->fmtpos++;
14333 }
14334 }
14335 }
14336 if (ctx->fmtcnt < 0) {
14337 PyErr_SetString(PyExc_ValueError,
14338 "incomplete format");
14339 return -1;
14340 }
14341 return 0;
14342
14343#undef FORMAT_READ
14344}
14345
14346/* Format one argument. Supported conversion specifiers:
14347
14348 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014349 - "i", "d", "u": int or float
14350 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014351 - "e", "E", "f", "F", "g", "G": float
14352 - "c": int or str (1 character)
14353
Victor Stinner8dbd4212012-12-04 09:30:24 +010014354 When possible, the output is written directly into the Unicode writer
14355 (ctx->writer). A string is created when padding is required.
14356
Victor Stinnera47082312012-10-04 02:19:54 +020014357 Return 0 if the argument has been formatted into *p_str,
14358 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014359 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014360static int
14361unicode_format_arg_format(struct unicode_formatter_t *ctx,
14362 struct unicode_format_arg_t *arg,
14363 PyObject **p_str)
14364{
14365 PyObject *v;
14366 _PyUnicodeWriter *writer = &ctx->writer;
14367
14368 if (ctx->fmtcnt == 0)
14369 ctx->writer.overallocate = 0;
14370
14371 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014372 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014373 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014374 return 1;
14375 }
14376
14377 v = unicode_format_getnextarg(ctx);
14378 if (v == NULL)
14379 return -1;
14380
Victor Stinnera47082312012-10-04 02:19:54 +020014381
14382 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014383 case 's':
14384 case 'r':
14385 case 'a':
14386 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14387 /* Fast path */
14388 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14389 return -1;
14390 return 1;
14391 }
14392
14393 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14394 *p_str = v;
14395 Py_INCREF(*p_str);
14396 }
14397 else {
14398 if (arg->ch == 's')
14399 *p_str = PyObject_Str(v);
14400 else if (arg->ch == 'r')
14401 *p_str = PyObject_Repr(v);
14402 else
14403 *p_str = PyObject_ASCII(v);
14404 }
14405 break;
14406
14407 case 'i':
14408 case 'd':
14409 case 'u':
14410 case 'o':
14411 case 'x':
14412 case 'X':
14413 {
14414 int ret = mainformatlong(v, arg, p_str, writer);
14415 if (ret != 0)
14416 return ret;
14417 arg->sign = 1;
14418 break;
14419 }
14420
14421 case 'e':
14422 case 'E':
14423 case 'f':
14424 case 'F':
14425 case 'g':
14426 case 'G':
14427 if (arg->width == -1 && arg->prec == -1
14428 && !(arg->flags & (F_SIGN | F_BLANK)))
14429 {
14430 /* Fast path */
14431 if (formatfloat(v, arg, NULL, writer) == -1)
14432 return -1;
14433 return 1;
14434 }
14435
14436 arg->sign = 1;
14437 if (formatfloat(v, arg, p_str, NULL) == -1)
14438 return -1;
14439 break;
14440
14441 case 'c':
14442 {
14443 Py_UCS4 ch = formatchar(v);
14444 if (ch == (Py_UCS4) -1)
14445 return -1;
14446 if (arg->width == -1 && arg->prec == -1) {
14447 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014448 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014449 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014450 return 1;
14451 }
14452 *p_str = PyUnicode_FromOrdinal(ch);
14453 break;
14454 }
14455
14456 default:
14457 PyErr_Format(PyExc_ValueError,
14458 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014459 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014460 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14461 (int)arg->ch,
14462 ctx->fmtpos - 1);
14463 return -1;
14464 }
14465 if (*p_str == NULL)
14466 return -1;
14467 assert (PyUnicode_Check(*p_str));
14468 return 0;
14469}
14470
14471static int
14472unicode_format_arg_output(struct unicode_formatter_t *ctx,
14473 struct unicode_format_arg_t *arg,
14474 PyObject *str)
14475{
14476 Py_ssize_t len;
14477 enum PyUnicode_Kind kind;
14478 void *pbuf;
14479 Py_ssize_t pindex;
14480 Py_UCS4 signchar;
14481 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014482 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014483 Py_ssize_t sublen;
14484 _PyUnicodeWriter *writer = &ctx->writer;
14485 Py_UCS4 fill;
14486
14487 fill = ' ';
14488 if (arg->sign && arg->flags & F_ZERO)
14489 fill = '0';
14490
14491 if (PyUnicode_READY(str) == -1)
14492 return -1;
14493
14494 len = PyUnicode_GET_LENGTH(str);
14495 if ((arg->width == -1 || arg->width <= len)
14496 && (arg->prec == -1 || arg->prec >= len)
14497 && !(arg->flags & (F_SIGN | F_BLANK)))
14498 {
14499 /* Fast path */
14500 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14501 return -1;
14502 return 0;
14503 }
14504
14505 /* Truncate the string for "s", "r" and "a" formats
14506 if the precision is set */
14507 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14508 if (arg->prec >= 0 && len > arg->prec)
14509 len = arg->prec;
14510 }
14511
14512 /* Adjust sign and width */
14513 kind = PyUnicode_KIND(str);
14514 pbuf = PyUnicode_DATA(str);
14515 pindex = 0;
14516 signchar = '\0';
14517 if (arg->sign) {
14518 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14519 if (ch == '-' || ch == '+') {
14520 signchar = ch;
14521 len--;
14522 pindex++;
14523 }
14524 else if (arg->flags & F_SIGN)
14525 signchar = '+';
14526 else if (arg->flags & F_BLANK)
14527 signchar = ' ';
14528 else
14529 arg->sign = 0;
14530 }
14531 if (arg->width < len)
14532 arg->width = len;
14533
14534 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014535 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014536 if (!(arg->flags & F_LJUST)) {
14537 if (arg->sign) {
14538 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014539 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014540 }
14541 else {
14542 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014543 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014544 }
14545 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014546 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14547 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014548 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014549 }
14550
Victor Stinnera47082312012-10-04 02:19:54 +020014551 buflen = arg->width;
14552 if (arg->sign && len == arg->width)
14553 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014554 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014555 return -1;
14556
14557 /* Write the sign if needed */
14558 if (arg->sign) {
14559 if (fill != ' ') {
14560 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14561 writer->pos += 1;
14562 }
14563 if (arg->width > len)
14564 arg->width--;
14565 }
14566
14567 /* Write the numeric prefix for "x", "X" and "o" formats
14568 if the alternate form is used.
14569 For example, write "0x" for the "%#x" format. */
14570 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14571 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14572 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14573 if (fill != ' ') {
14574 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14575 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14576 writer->pos += 2;
14577 pindex += 2;
14578 }
14579 arg->width -= 2;
14580 if (arg->width < 0)
14581 arg->width = 0;
14582 len -= 2;
14583 }
14584
14585 /* Pad left with the fill character if needed */
14586 if (arg->width > len && !(arg->flags & F_LJUST)) {
14587 sublen = arg->width - len;
14588 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14589 writer->pos += sublen;
14590 arg->width = len;
14591 }
14592
14593 /* If padding with spaces: write sign if needed and/or numeric prefix if
14594 the alternate form is used */
14595 if (fill == ' ') {
14596 if (arg->sign) {
14597 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14598 writer->pos += 1;
14599 }
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 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14604 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14605 writer->pos += 2;
14606 pindex += 2;
14607 }
14608 }
14609
14610 /* Write characters */
14611 if (len) {
14612 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14613 str, pindex, len);
14614 writer->pos += len;
14615 }
14616
14617 /* Pad right with the fill character if needed */
14618 if (arg->width > len) {
14619 sublen = arg->width - len;
14620 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14621 writer->pos += sublen;
14622 }
14623 return 0;
14624}
14625
14626/* Helper of PyUnicode_Format(): format one arg.
14627 Return 0 on success, raise an exception and return -1 on error. */
14628static int
14629unicode_format_arg(struct unicode_formatter_t *ctx)
14630{
14631 struct unicode_format_arg_t arg;
14632 PyObject *str;
14633 int ret;
14634
Victor Stinner8dbd4212012-12-04 09:30:24 +010014635 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14636 arg.flags = 0;
14637 arg.width = -1;
14638 arg.prec = -1;
14639 arg.sign = 0;
14640 str = NULL;
14641
Victor Stinnera47082312012-10-04 02:19:54 +020014642 ret = unicode_format_arg_parse(ctx, &arg);
14643 if (ret == -1)
14644 return -1;
14645
14646 ret = unicode_format_arg_format(ctx, &arg, &str);
14647 if (ret == -1)
14648 return -1;
14649
14650 if (ret != 1) {
14651 ret = unicode_format_arg_output(ctx, &arg, str);
14652 Py_DECREF(str);
14653 if (ret == -1)
14654 return -1;
14655 }
14656
14657 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14658 PyErr_SetString(PyExc_TypeError,
14659 "not all arguments converted during string formatting");
14660 return -1;
14661 }
14662 return 0;
14663}
14664
Alexander Belopolsky40018472011-02-26 01:02:56 +000014665PyObject *
14666PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014667{
Victor Stinnera47082312012-10-04 02:19:54 +020014668 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014669
Guido van Rossumd57fd912000-03-10 22:53:23 +000014670 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014671 PyErr_BadInternalCall();
14672 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014673 }
Victor Stinnera47082312012-10-04 02:19:54 +020014674
14675 ctx.fmtstr = PyUnicode_FromObject(format);
14676 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014677 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014678 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14679 Py_DECREF(ctx.fmtstr);
14680 return NULL;
14681 }
14682 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14683 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14684 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14685 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014686
Victor Stinner8f674cc2013-04-17 23:02:17 +020014687 _PyUnicodeWriter_Init(&ctx.writer);
14688 ctx.writer.min_length = ctx.fmtcnt + 100;
14689 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014690
Guido van Rossumd57fd912000-03-10 22:53:23 +000014691 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014692 ctx.arglen = PyTuple_Size(args);
14693 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014694 }
14695 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014696 ctx.arglen = -1;
14697 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014698 }
Victor Stinnera47082312012-10-04 02:19:54 +020014699 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014700 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014701 ctx.dict = args;
14702 else
14703 ctx.dict = NULL;
14704 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014705
Victor Stinnera47082312012-10-04 02:19:54 +020014706 while (--ctx.fmtcnt >= 0) {
14707 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014708 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014709
14710 nonfmtpos = ctx.fmtpos++;
14711 while (ctx.fmtcnt >= 0 &&
14712 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14713 ctx.fmtpos++;
14714 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014715 }
Victor Stinnera47082312012-10-04 02:19:54 +020014716 if (ctx.fmtcnt < 0) {
14717 ctx.fmtpos--;
14718 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014719 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014720
Victor Stinnercfc4c132013-04-03 01:48:39 +020014721 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14722 nonfmtpos, ctx.fmtpos) < 0)
14723 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014724 }
14725 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014726 ctx.fmtpos++;
14727 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014728 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014729 }
14730 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014731
Victor Stinnera47082312012-10-04 02:19:54 +020014732 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014733 PyErr_SetString(PyExc_TypeError,
14734 "not all arguments converted during string formatting");
14735 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014736 }
14737
Victor Stinnera47082312012-10-04 02:19:54 +020014738 if (ctx.args_owned) {
14739 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014740 }
Victor Stinnera47082312012-10-04 02:19:54 +020014741 Py_DECREF(ctx.fmtstr);
14742 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014743
Benjamin Peterson29060642009-01-31 22:14:21 +000014744 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014745 Py_DECREF(ctx.fmtstr);
14746 _PyUnicodeWriter_Dealloc(&ctx.writer);
14747 if (ctx.args_owned) {
14748 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014749 }
14750 return NULL;
14751}
14752
Jeremy Hylton938ace62002-07-17 16:30:39 +000014753static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014754unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14755
Tim Peters6d6c1a32001-08-02 04:15:00 +000014756static PyObject *
14757unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14758{
Benjamin Peterson29060642009-01-31 22:14:21 +000014759 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014760 static char *kwlist[] = {"object", "encoding", "errors", 0};
14761 char *encoding = NULL;
14762 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014763
Benjamin Peterson14339b62009-01-31 16:36:08 +000014764 if (type != &PyUnicode_Type)
14765 return unicode_subtype_new(type, args, kwds);
14766 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014767 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014768 return NULL;
14769 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014770 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014771 if (encoding == NULL && errors == NULL)
14772 return PyObject_Str(x);
14773 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014774 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014775}
14776
Guido van Rossume023fe02001-08-30 03:12:59 +000014777static PyObject *
14778unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14779{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014780 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014781 Py_ssize_t length, char_size;
14782 int share_wstr, share_utf8;
14783 unsigned int kind;
14784 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014785
Benjamin Peterson14339b62009-01-31 16:36:08 +000014786 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014787
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014788 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014789 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014790 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014791 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014792 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014793 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014794 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014795 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014796
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014797 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014798 if (self == NULL) {
14799 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014800 return NULL;
14801 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014802 kind = PyUnicode_KIND(unicode);
14803 length = PyUnicode_GET_LENGTH(unicode);
14804
14805 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014806#ifdef Py_DEBUG
14807 _PyUnicode_HASH(self) = -1;
14808#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014809 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014810#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014811 _PyUnicode_STATE(self).interned = 0;
14812 _PyUnicode_STATE(self).kind = kind;
14813 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014814 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014815 _PyUnicode_STATE(self).ready = 1;
14816 _PyUnicode_WSTR(self) = NULL;
14817 _PyUnicode_UTF8_LENGTH(self) = 0;
14818 _PyUnicode_UTF8(self) = NULL;
14819 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014820 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014821
14822 share_utf8 = 0;
14823 share_wstr = 0;
14824 if (kind == PyUnicode_1BYTE_KIND) {
14825 char_size = 1;
14826 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14827 share_utf8 = 1;
14828 }
14829 else if (kind == PyUnicode_2BYTE_KIND) {
14830 char_size = 2;
14831 if (sizeof(wchar_t) == 2)
14832 share_wstr = 1;
14833 }
14834 else {
14835 assert(kind == PyUnicode_4BYTE_KIND);
14836 char_size = 4;
14837 if (sizeof(wchar_t) == 4)
14838 share_wstr = 1;
14839 }
14840
14841 /* Ensure we won't overflow the length. */
14842 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14843 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014844 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014845 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014846 data = PyObject_MALLOC((length + 1) * char_size);
14847 if (data == NULL) {
14848 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014849 goto onError;
14850 }
14851
Victor Stinnerc3c74152011-10-02 20:39:55 +020014852 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014853 if (share_utf8) {
14854 _PyUnicode_UTF8_LENGTH(self) = length;
14855 _PyUnicode_UTF8(self) = data;
14856 }
14857 if (share_wstr) {
14858 _PyUnicode_WSTR_LENGTH(self) = length;
14859 _PyUnicode_WSTR(self) = (wchar_t *)data;
14860 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014861
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014862 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014863 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014864 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014865#ifdef Py_DEBUG
14866 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14867#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014868 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014869 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014870
14871onError:
14872 Py_DECREF(unicode);
14873 Py_DECREF(self);
14874 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014875}
14876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014877PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014878"str(object='') -> str\n\
14879str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014880\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014881Create a new string object from the given object. If encoding or\n\
14882errors is specified, then the object must expose a data buffer\n\
14883that will be decoded using the given encoding and error handler.\n\
14884Otherwise, returns the result of object.__str__() (if defined)\n\
14885or repr(object).\n\
14886encoding defaults to sys.getdefaultencoding().\n\
14887errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014888
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014889static PyObject *unicode_iter(PyObject *seq);
14890
Guido van Rossumd57fd912000-03-10 22:53:23 +000014891PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014892 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014893 "str", /* tp_name */
14894 sizeof(PyUnicodeObject), /* tp_size */
14895 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014896 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014897 (destructor)unicode_dealloc, /* tp_dealloc */
14898 0, /* tp_print */
14899 0, /* tp_getattr */
14900 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014901 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014902 unicode_repr, /* tp_repr */
14903 &unicode_as_number, /* tp_as_number */
14904 &unicode_as_sequence, /* tp_as_sequence */
14905 &unicode_as_mapping, /* tp_as_mapping */
14906 (hashfunc) unicode_hash, /* tp_hash*/
14907 0, /* tp_call*/
14908 (reprfunc) unicode_str, /* tp_str */
14909 PyObject_GenericGetAttr, /* tp_getattro */
14910 0, /* tp_setattro */
14911 0, /* tp_as_buffer */
14912 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014913 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014914 unicode_doc, /* tp_doc */
14915 0, /* tp_traverse */
14916 0, /* tp_clear */
14917 PyUnicode_RichCompare, /* tp_richcompare */
14918 0, /* tp_weaklistoffset */
14919 unicode_iter, /* tp_iter */
14920 0, /* tp_iternext */
14921 unicode_methods, /* tp_methods */
14922 0, /* tp_members */
14923 0, /* tp_getset */
14924 &PyBaseObject_Type, /* tp_base */
14925 0, /* tp_dict */
14926 0, /* tp_descr_get */
14927 0, /* tp_descr_set */
14928 0, /* tp_dictoffset */
14929 0, /* tp_init */
14930 0, /* tp_alloc */
14931 unicode_new, /* tp_new */
14932 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014933};
14934
14935/* Initialize the Unicode implementation */
14936
Victor Stinner3a50e702011-10-18 21:21:00 +020014937int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014938{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014939 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014940 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014941 0x000A, /* LINE FEED */
14942 0x000D, /* CARRIAGE RETURN */
14943 0x001C, /* FILE SEPARATOR */
14944 0x001D, /* GROUP SEPARATOR */
14945 0x001E, /* RECORD SEPARATOR */
14946 0x0085, /* NEXT LINE */
14947 0x2028, /* LINE SEPARATOR */
14948 0x2029, /* PARAGRAPH SEPARATOR */
14949 };
14950
Fred Drakee4315f52000-05-09 19:53:39 +000014951 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014952 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014953 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014954 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014955 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014956
Guido van Rossumcacfc072002-05-24 19:01:59 +000014957 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014958 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014959
14960 /* initialize the linebreak bloom filter */
14961 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014962 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014963 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014964
Christian Heimes26532f72013-07-20 14:57:16 +020014965 if (PyType_Ready(&EncodingMapType) < 0)
14966 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014967
Benjamin Petersonc4311282012-10-30 23:21:10 -040014968 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14969 Py_FatalError("Can't initialize field name iterator type");
14970
14971 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14972 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014973
Victor Stinner3a50e702011-10-18 21:21:00 +020014974 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014975}
14976
14977/* Finalize the Unicode implementation */
14978
Christian Heimesa156e092008-02-16 07:38:31 +000014979int
14980PyUnicode_ClearFreeList(void)
14981{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014982 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014983}
14984
Guido van Rossumd57fd912000-03-10 22:53:23 +000014985void
Thomas Wouters78890102000-07-22 19:25:51 +000014986_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014987{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014988 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014989
Serhiy Storchaka05997252013-01-26 12:14:02 +020014990 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014991
Serhiy Storchaka05997252013-01-26 12:14:02 +020014992 for (i = 0; i < 256; i++)
14993 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014994 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014995 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014996}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014997
Walter Dörwald16807132007-05-25 13:52:07 +000014998void
14999PyUnicode_InternInPlace(PyObject **p)
15000{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015001 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015002 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015003#ifdef Py_DEBUG
15004 assert(s != NULL);
15005 assert(_PyUnicode_CHECK(s));
15006#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015007 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015008 return;
15009#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015010 /* If it's a subclass, we don't really know what putting
15011 it in the interned dict might do. */
15012 if (!PyUnicode_CheckExact(s))
15013 return;
15014 if (PyUnicode_CHECK_INTERNED(s))
15015 return;
15016 if (interned == NULL) {
15017 interned = PyDict_New();
15018 if (interned == NULL) {
15019 PyErr_Clear(); /* Don't leave an exception */
15020 return;
15021 }
15022 }
15023 /* It might be that the GetItem call fails even
15024 though the key is present in the dictionary,
15025 namely when this happens during a stack overflow. */
15026 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015027 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015028 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015029
Victor Stinnerf0335102013-04-14 19:13:03 +020015030 if (t) {
15031 Py_INCREF(t);
15032 Py_DECREF(*p);
15033 *p = t;
15034 return;
15035 }
Walter Dörwald16807132007-05-25 13:52:07 +000015036
Benjamin Peterson14339b62009-01-31 16:36:08 +000015037 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015038 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015039 PyErr_Clear();
15040 PyThreadState_GET()->recursion_critical = 0;
15041 return;
15042 }
15043 PyThreadState_GET()->recursion_critical = 0;
15044 /* The two references in interned are not counted by refcnt.
15045 The deallocator will take care of this */
15046 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015047 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015048}
15049
15050void
15051PyUnicode_InternImmortal(PyObject **p)
15052{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 PyUnicode_InternInPlace(p);
15054 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015055 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015056 Py_INCREF(*p);
15057 }
Walter Dörwald16807132007-05-25 13:52:07 +000015058}
15059
15060PyObject *
15061PyUnicode_InternFromString(const char *cp)
15062{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015063 PyObject *s = PyUnicode_FromString(cp);
15064 if (s == NULL)
15065 return NULL;
15066 PyUnicode_InternInPlace(&s);
15067 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015068}
15069
Alexander Belopolsky40018472011-02-26 01:02:56 +000015070void
15071_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015072{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015073 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015074 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015075 Py_ssize_t i, n;
15076 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015077
Benjamin Peterson14339b62009-01-31 16:36:08 +000015078 if (interned == NULL || !PyDict_Check(interned))
15079 return;
15080 keys = PyDict_Keys(interned);
15081 if (keys == NULL || !PyList_Check(keys)) {
15082 PyErr_Clear();
15083 return;
15084 }
Walter Dörwald16807132007-05-25 13:52:07 +000015085
Benjamin Peterson14339b62009-01-31 16:36:08 +000015086 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15087 detector, interned unicode strings are not forcibly deallocated;
15088 rather, we give them their stolen references back, and then clear
15089 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015090
Benjamin Peterson14339b62009-01-31 16:36:08 +000015091 n = PyList_GET_SIZE(keys);
15092 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015093 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015095 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015096 if (PyUnicode_READY(s) == -1) {
15097 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015098 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015099 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015100 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015101 case SSTATE_NOT_INTERNED:
15102 /* XXX Shouldn't happen */
15103 break;
15104 case SSTATE_INTERNED_IMMORTAL:
15105 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015106 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 break;
15108 case SSTATE_INTERNED_MORTAL:
15109 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015110 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015111 break;
15112 default:
15113 Py_FatalError("Inconsistent interned string state.");
15114 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015115 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015116 }
15117 fprintf(stderr, "total size of all interned strings: "
15118 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15119 "mortal/immortal\n", mortal_size, immortal_size);
15120 Py_DECREF(keys);
15121 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015122 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015123}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015124
15125
15126/********************* Unicode Iterator **************************/
15127
15128typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015129 PyObject_HEAD
15130 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015131 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015132} unicodeiterobject;
15133
15134static void
15135unicodeiter_dealloc(unicodeiterobject *it)
15136{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015137 _PyObject_GC_UNTRACK(it);
15138 Py_XDECREF(it->it_seq);
15139 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015140}
15141
15142static int
15143unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15144{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 Py_VISIT(it->it_seq);
15146 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015147}
15148
15149static PyObject *
15150unicodeiter_next(unicodeiterobject *it)
15151{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015152 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015153
Benjamin Peterson14339b62009-01-31 16:36:08 +000015154 assert(it != NULL);
15155 seq = it->it_seq;
15156 if (seq == NULL)
15157 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015158 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015160 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15161 int kind = PyUnicode_KIND(seq);
15162 void *data = PyUnicode_DATA(seq);
15163 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15164 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015165 if (item != NULL)
15166 ++it->it_index;
15167 return item;
15168 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015169
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 Py_DECREF(seq);
15171 it->it_seq = NULL;
15172 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015173}
15174
15175static PyObject *
15176unicodeiter_len(unicodeiterobject *it)
15177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 Py_ssize_t len = 0;
15179 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015180 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015182}
15183
15184PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15185
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015186static PyObject *
15187unicodeiter_reduce(unicodeiterobject *it)
15188{
15189 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015190 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015191 it->it_seq, it->it_index);
15192 } else {
15193 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15194 if (u == NULL)
15195 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015196 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015197 }
15198}
15199
15200PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15201
15202static PyObject *
15203unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15204{
15205 Py_ssize_t index = PyLong_AsSsize_t(state);
15206 if (index == -1 && PyErr_Occurred())
15207 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015208 if (it->it_seq != NULL) {
15209 if (index < 0)
15210 index = 0;
15211 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15212 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15213 it->it_index = index;
15214 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015215 Py_RETURN_NONE;
15216}
15217
15218PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15219
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015220static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015221 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015222 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015223 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15224 reduce_doc},
15225 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15226 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015227 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015228};
15229
15230PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015231 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15232 "str_iterator", /* tp_name */
15233 sizeof(unicodeiterobject), /* tp_basicsize */
15234 0, /* tp_itemsize */
15235 /* methods */
15236 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15237 0, /* tp_print */
15238 0, /* tp_getattr */
15239 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015240 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015241 0, /* tp_repr */
15242 0, /* tp_as_number */
15243 0, /* tp_as_sequence */
15244 0, /* tp_as_mapping */
15245 0, /* tp_hash */
15246 0, /* tp_call */
15247 0, /* tp_str */
15248 PyObject_GenericGetAttr, /* tp_getattro */
15249 0, /* tp_setattro */
15250 0, /* tp_as_buffer */
15251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15252 0, /* tp_doc */
15253 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15254 0, /* tp_clear */
15255 0, /* tp_richcompare */
15256 0, /* tp_weaklistoffset */
15257 PyObject_SelfIter, /* tp_iter */
15258 (iternextfunc)unicodeiter_next, /* tp_iternext */
15259 unicodeiter_methods, /* tp_methods */
15260 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015261};
15262
15263static PyObject *
15264unicode_iter(PyObject *seq)
15265{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015267
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 if (!PyUnicode_Check(seq)) {
15269 PyErr_BadInternalCall();
15270 return NULL;
15271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015272 if (PyUnicode_READY(seq) == -1)
15273 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015274 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15275 if (it == NULL)
15276 return NULL;
15277 it->it_index = 0;
15278 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015279 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 _PyObject_GC_TRACK(it);
15281 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015282}
15283
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015284
15285size_t
15286Py_UNICODE_strlen(const Py_UNICODE *u)
15287{
15288 int res = 0;
15289 while(*u++)
15290 res++;
15291 return res;
15292}
15293
15294Py_UNICODE*
15295Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15296{
15297 Py_UNICODE *u = s1;
15298 while ((*u++ = *s2++));
15299 return s1;
15300}
15301
15302Py_UNICODE*
15303Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15304{
15305 Py_UNICODE *u = s1;
15306 while ((*u++ = *s2++))
15307 if (n-- == 0)
15308 break;
15309 return s1;
15310}
15311
15312Py_UNICODE*
15313Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15314{
15315 Py_UNICODE *u1 = s1;
15316 u1 += Py_UNICODE_strlen(u1);
15317 Py_UNICODE_strcpy(u1, s2);
15318 return s1;
15319}
15320
15321int
15322Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15323{
15324 while (*s1 && *s2 && *s1 == *s2)
15325 s1++, s2++;
15326 if (*s1 && *s2)
15327 return (*s1 < *s2) ? -1 : +1;
15328 if (*s1)
15329 return 1;
15330 if (*s2)
15331 return -1;
15332 return 0;
15333}
15334
15335int
15336Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15337{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015338 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015339 for (; n != 0; n--) {
15340 u1 = *s1;
15341 u2 = *s2;
15342 if (u1 != u2)
15343 return (u1 < u2) ? -1 : +1;
15344 if (u1 == '\0')
15345 return 0;
15346 s1++;
15347 s2++;
15348 }
15349 return 0;
15350}
15351
15352Py_UNICODE*
15353Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15354{
15355 const Py_UNICODE *p;
15356 for (p = s; *p; p++)
15357 if (*p == c)
15358 return (Py_UNICODE*)p;
15359 return NULL;
15360}
15361
15362Py_UNICODE*
15363Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15364{
15365 const Py_UNICODE *p;
15366 p = s + Py_UNICODE_strlen(s);
15367 while (p != s) {
15368 p--;
15369 if (*p == c)
15370 return (Py_UNICODE*)p;
15371 }
15372 return NULL;
15373}
Victor Stinner331ea922010-08-10 16:37:20 +000015374
Victor Stinner71133ff2010-09-01 23:43:53 +000015375Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015376PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015377{
Victor Stinner577db2c2011-10-11 22:12:48 +020015378 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015379 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015381 if (!PyUnicode_Check(unicode)) {
15382 PyErr_BadArgument();
15383 return NULL;
15384 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015385 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015386 if (u == NULL)
15387 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015388 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015389 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015390 PyErr_NoMemory();
15391 return NULL;
15392 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015393 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015394 size *= sizeof(Py_UNICODE);
15395 copy = PyMem_Malloc(size);
15396 if (copy == NULL) {
15397 PyErr_NoMemory();
15398 return NULL;
15399 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015400 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015401 return copy;
15402}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015403
Georg Brandl66c221e2010-10-14 07:04:07 +000015404/* A _string module, to export formatter_parser and formatter_field_name_split
15405 to the string.Formatter class implemented in Python. */
15406
15407static PyMethodDef _string_methods[] = {
15408 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15409 METH_O, PyDoc_STR("split the argument as a field name")},
15410 {"formatter_parser", (PyCFunction) formatter_parser,
15411 METH_O, PyDoc_STR("parse the argument as a format string")},
15412 {NULL, NULL}
15413};
15414
15415static struct PyModuleDef _string_module = {
15416 PyModuleDef_HEAD_INIT,
15417 "_string",
15418 PyDoc_STR("string helper module"),
15419 0,
15420 _string_methods,
15421 NULL,
15422 NULL,
15423 NULL,
15424 NULL
15425};
15426
15427PyMODINIT_FUNC
15428PyInit__string(void)
15429{
15430 return PyModule_Create(&_string_module);
15431}
15432
15433
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015434#ifdef __cplusplus
15435}
15436#endif